<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>QuerySet API reference &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../../index.html" />
    <link rel="up" title="Models" href="index.html" />
    <link rel="next" title="Query-related classes" href="queries.html" />
    <link rel="prev" title="Model instance reference" href="instances.html" />



 
<script type="text/javascript" src="../../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="instances.html" title="Model instance reference">previous</a>
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="queries.html" title="Query-related classes">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-models-querysets">
            
  <div class="section" id="s-queryset-api-reference">
<span id="queryset-api-reference"></span><h1>QuerySet API reference<a class="headerlink" href="#queryset-api-reference" title="Permalink to this headline">¶</a></h1>
<p>This document describes the details of the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> API. It builds on the
material presented in the <a class="reference internal" href="../../topics/db/models.html"><em>model</em></a> and <a class="reference internal" href="../../topics/db/queries.html"><em>database
query</em></a> guides, so you&#8217;ll probably want to read and
understand those documents before reading this one.</p>
<p>Throughout this reference we&#8217;ll use the <a class="reference internal" href="../../topics/db/queries.html#queryset-model-example"><em>example Weblog models</em></a> presented in the <a class="reference internal" href="../../topics/db/queries.html"><em>database query guide</em></a>.</p>
<div class="section" id="s-when-querysets-are-evaluated">
<span id="s-id1"></span><span id="when-querysets-are-evaluated"></span><span id="id1"></span><h2>When QuerySets are evaluated<a class="headerlink" href="#when-querysets-are-evaluated" title="Permalink to this headline">¶</a></h2>
<p>Internally, a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> can be constructed, filtered, sliced, and generally
passed around without actually hitting the database. No database activity
actually occurs until you do something to evaluate the queryset.</p>
<p>You can evaluate a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> in the following ways:</p>
<ul>
<li><p class="first"><strong>Iteration.</strong> A <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is iterable, and it executes its database
query the first time you iterate over it. For example, this will print
the headline of all entries in the database:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">headline</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: Don&#8217;t use this if all you want to do is determine if at least one
result exists. It&#8217;s more efficient to use <a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><tt class="xref py py-meth docutils literal"><span class="pre">exists()</span></tt></a>.</p>
</li>
<li><p class="first"><strong>Slicing.</strong> As explained in <a class="reference internal" href="../../topics/db/queries.html#limiting-querysets"><em>Limiting QuerySets</em></a>, a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> can
be sliced, using Python&#8217;s array-slicing syntax. Slicing an unevaluated
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> usually returns another unevaluated <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, but Django
will execute the database query if you use the &#8220;step&#8221; parameter of slice
syntax, and will return a list. Slicing a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that has been
evaluated also returns a list.</p>
<p>Also note that even though slicing an unevaluated <tt class="docutils literal"><span class="pre">QuerySet</span></tt> returns
another unevaluated <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, modifying it further (e.g., adding
more filters, or modifying ordering) is not allowed, since that does not
translate well into SQL and it would not have a clear meaning either.</p>
</li>
<li><p class="first"><strong>Pickling/Caching.</strong> See the following section for details of what
is involved when <a class="reference internal" href="#pickling-querysets">pickling QuerySets</a>. The important thing for the
purposes of this section is that the results are read from the database.</p>
</li>
<li><p class="first"><strong>repr().</strong> A <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is evaluated when you call <tt class="docutils literal"><span class="pre">repr()</span></tt> on it.
This is for convenience in the Python interactive interpreter, so you can
immediately see your results when using the API interactively.</p>
</li>
<li><p class="first"><strong>len().</strong> A <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is evaluated when you call <tt class="docutils literal"><span class="pre">len()</span></tt> on it.
This, as you might expect, returns the length of the result list.</p>
<p>Note: If you only need to determine the number of records in the set (and
don&#8217;t need the actual objects), it&#8217;s much more efficient to handle a count
at the database level using SQL&#8217;s <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">COUNT(*)</span></tt>. Django provides a
<a class="reference internal" href="#django.db.models.query.QuerySet.count" title="django.db.models.query.QuerySet.count"><tt class="xref py py-meth docutils literal"><span class="pre">count()</span></tt></a> method for precisely this reason.</p>
</li>
<li><p class="first"><strong>list().</strong> Force evaluation of a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> by calling <tt class="docutils literal"><span class="pre">list()</span></tt> on
it. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">entry_list</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
</li>
<li><p class="first"><strong>bool().</strong> Testing a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> in a boolean context, such as using
<tt class="docutils literal"><span class="pre">bool()</span></tt>, <tt class="docutils literal"><span class="pre">or</span></tt>, <tt class="docutils literal"><span class="pre">and</span></tt> or an <tt class="docutils literal"><span class="pre">if</span></tt> statement, will cause the query
to be executed. If there is at least one result, the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is
<tt class="docutils literal"><span class="pre">True</span></tt>, otherwise <tt class="docutils literal"><span class="pre">False</span></tt>. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&quot;Test&quot;</span><span class="p">):</span>
   <span class="k">print</span><span class="p">(</span><span class="s">&quot;There is at least one Entry with the headline Test&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: If you only want to determine if at least one result exists (and don&#8217;t
need the actual objects), it&#8217;s more efficient to use <a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><tt class="xref py py-meth docutils literal"><span class="pre">exists()</span></tt></a>.</p>
</li>
</ul>
<div class="section" id="s-pickling-querysets">
<span id="s-id2"></span><span id="pickling-querysets"></span><span id="id2"></span><h3>Pickling QuerySets<a class="headerlink" href="#pickling-querysets" title="Permalink to this headline">¶</a></h3>
<p>If you <a class="reference external" href="http://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">pickle</span></tt></a> a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, this will force all the results to be loaded
into memory prior to pickling. Pickling is usually used as a precursor to
caching and when the cached queryset is reloaded, you want the results to
already be present and ready for use (reading from the database can take some
time, defeating the purpose of caching). This means that when you unpickle a
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>, it contains the results at the moment it was pickled, rather
than the results that are currently in the database.</p>
<p>If you only want to pickle the necessary information to recreate the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> from the database at a later time, pickle the <tt class="docutils literal"><span class="pre">query</span></tt> attribute
of the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. You can then recreate the original <tt class="docutils literal"><span class="pre">QuerySet</span></tt> (without
any results loaded) using some code like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">query</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>     <span class="c"># Assuming &#39;s&#39; is the pickled string.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span> <span class="o">=</span> <span class="n">MyModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qs</span><span class="o">.</span><span class="n">query</span> <span class="o">=</span> <span class="n">query</span>            <span class="c"># Restore the original &#39;query&#39;.</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">query</span></tt> attribute is an opaque object. It represents the internals of
the query construction and is not part of the public API. However, it is safe
(and fully supported) to pickle and unpickle the attribute&#8217;s contents as
described here.</p>
<div class="admonition-you-can-t-share-pickles-between-versions admonition">
<p class="first admonition-title">You can&#8217;t share pickles between versions</p>
<p class="last">Pickles of <tt class="docutils literal"><span class="pre">QuerySets</span></tt> are only valid for the version of Django that
was used to generate them. If you generate a pickle using Django
version N, there is no guarantee that pickle will be readable with
Django version N+1. Pickles should not be used as part of a long-term
archival strategy.</p>
</div>
</div>
</div>
<div class="section" id="s-queryset-api">
<span id="s-id3"></span><span id="queryset-api"></span><span id="id3"></span><h2>QuerySet API<a class="headerlink" href="#queryset-api" title="Permalink to this headline">¶</a></h2>
<p>Here&#8217;s the formal declaration of a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>:</p>
<dl class="class">
<dt id="django.db.models.query.QuerySet">
<em class="property">class </em><tt class="descname">QuerySet</tt>(<span class="optional">[</span><em>model=None</em>, <em>query=None</em>, <em>using=None</em><span class="optional">]</span>)<a class="reference internal" href="../../_modules/django/db/models/query.html#QuerySet"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.query.QuerySet" title="Permalink to this definition">¶</a></dt>
<dd><p>Usually when you&#8217;ll interact with a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> you&#8217;ll use it by
<a class="reference internal" href="../../topics/db/queries.html#chaining-filters"><em>chaining filters</em></a>. To make this work, most
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods return new querysets. These methods are covered in
detail later in this section.</p>
<p>The <tt class="docutils literal"><span class="pre">QuerySet</span></tt> class has two public attributes you can use for
introspection:</p>
<dl class="attribute">
<dt id="django.db.models.query.QuerySet.ordered">
<tt class="descname">ordered</tt><a class="reference internal" href="../../_modules/django/db/models/query.html#QuerySet.ordered"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.query.QuerySet.ordered" title="Permalink to this definition">¶</a></dt>
<dd><p><tt class="docutils literal"><span class="pre">True</span></tt> if the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is ordered — i.e. has an
<a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> clause or a default ordering on the model.
<tt class="docutils literal"><span class="pre">False</span></tt> otherwise.</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.query.QuerySet.db">
<tt class="descname">db</tt><a class="reference internal" href="../../_modules/django/db/models/query.html#QuerySet.db"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.db.models.query.QuerySet.db" title="Permalink to this definition">¶</a></dt>
<dd><p>The database that will be used if this query is executed now.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <tt class="docutils literal"><span class="pre">query</span></tt> parameter to <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> exists so that specialized
query subclasses such as
<a class="reference internal" href="../contrib/gis/geoquerysets.html#django.contrib.gis.db.models.GeoQuerySet" title="django.contrib.gis.db.models.GeoQuerySet"><tt class="xref py py-class docutils literal"><span class="pre">GeoQuerySet</span></tt></a> can reconstruct
internal query state. The value of the parameter is an opaque
representation of that query state and is not part of a public API.
To put it simply: if you need to ask, you don&#8217;t need to use it.</p>
</div>
</dd></dl>

<div class="section" id="s-methods-that-return-new-querysets">
<span id="methods-that-return-new-querysets"></span><h3>Methods that return new QuerySets<a class="headerlink" href="#methods-that-return-new-querysets" title="Permalink to this headline">¶</a></h3>
<p>Django provides a range of <tt class="docutils literal"><span class="pre">QuerySet</span></tt> refinement methods that modify either
the types of results returned by the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> or the way its SQL query is
executed.</p>
<div class="section" id="s-filter">
<span id="filter"></span><h4>filter<a class="headerlink" href="#filter" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.filter">
<tt class="descname">filter</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.filter" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> containing objects that match the given lookup
parameters.</p>
<p>The lookup parameters (<tt class="docutils literal"><span class="pre">**kwargs</span></tt>) should be in the format described in
<a class="reference internal" href="#id4">Field lookups</a> below. Multiple parameters are joined via <tt class="docutils literal"><span class="pre">AND</span></tt> in the
underlying SQL statement.</p>
</div>
<div class="section" id="s-exclude">
<span id="exclude"></span><h4>exclude<a class="headerlink" href="#exclude" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.exclude">
<tt class="descname">exclude</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.exclude" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> containing objects that do <em>not</em> match the given
lookup parameters.</p>
<p>The lookup parameters (<tt class="docutils literal"><span class="pre">**kwargs</span></tt>) should be in the format described in
<a class="reference internal" href="#id4">Field lookups</a> below. Multiple parameters are joined via <tt class="docutils literal"><span class="pre">AND</span></tt> in the
underlying SQL statement, and the whole thing is enclosed in a <tt class="docutils literal"><span class="pre">NOT()</span></tt>.</p>
<p>This example excludes all entries whose <tt class="docutils literal"><span class="pre">pub_date</span></tt> is later than 2005-1-3
AND whose <tt class="docutils literal"><span class="pre">headline</span></tt> is &#8220;Hello&#8221;:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">headline</span><span class="o">=</span><span class="s">&#39;Hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In SQL terms, that evaluates to:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ...
WHERE NOT (pub_date &gt; &#39;2005-1-3&#39; AND headline = &#39;Hello&#39;)
</pre></div>
</div>
<p>This example excludes all entries whose <tt class="docutils literal"><span class="pre">pub_date</span></tt> is later than 2005-1-3
OR whose headline is &#8220;Hello&#8221;:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&#39;Hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In SQL terms, that evaluates to:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ...
WHERE NOT pub_date &gt; &#39;2005-1-3&#39;
AND NOT headline = &#39;Hello&#39;
</pre></div>
</div>
<p>Note the second example is more restrictive.</p>
</div>
<div class="section" id="s-annotate">
<span id="annotate"></span><h4>annotate<a class="headerlink" href="#annotate" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.annotate">
<tt class="descname">annotate</tt>(<em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.annotate" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Annotates each object in the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> with the provided list of
aggregate values (averages, sums, etc) that have been computed over
the objects that are related to the objects in the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.
Each argument to <tt class="docutils literal"><span class="pre">annotate()</span></tt> is an annotation that will be added
to each object in the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that is returned.</p>
<p>The aggregation functions that are provided by Django are described
in <a class="reference internal" href="#id5">Aggregation Functions</a> below.</p>
<p>Annotations specified using keyword arguments will use the keyword as
the alias for the annotation. Anonymous arguments will have an alias
generated for them based upon the name of the aggregate function and
the model field that is being aggregated.</p>
<p>For example, if you were manipulating a list of blogs, you may want
to determine how many entries have been made in each blog:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">Count</span><span class="p">(</span><span class="s">&#39;entry&#39;</span><span class="p">))</span>
<span class="go"># The name of the first blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">name</span>
<span class="go">&#39;Blogasaurus&#39;</span>
<span class="go"># The number of entries on the first blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">entry__count</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Blog</span></tt> model doesn&#8217;t define an <tt class="docutils literal"><span class="pre">entry__count</span></tt> attribute by itself,
but by using a keyword argument to specify the aggregate function, you can
control the name of the annotation:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="n">number_of_entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s">&#39;entry&#39;</span><span class="p">))</span>
<span class="go"># The number of entries on the first blog, using the name provided</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">number_of_entries</span>
<span class="go">42</span>
</pre></div>
</div>
<p>For an in-depth discussion of aggregation, see <a class="reference internal" href="../../topics/db/aggregation.html"><em>the topic guide on
Aggregation</em></a>.</p>
</div>
<div class="section" id="s-order-by">
<span id="order-by"></span><h4>order_by<a class="headerlink" href="#order-by" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.order_by">
<tt class="descname">order_by</tt>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.order_by" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>By default, results returned by a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> are ordered by the ordering
tuple given by the <tt class="docutils literal"><span class="pre">ordering</span></tt> option in the model&#8217;s <tt class="docutils literal"><span class="pre">Meta</span></tt>. You can
override this on a per-<tt class="docutils literal"><span class="pre">QuerySet</span></tt> basis by using the <tt class="docutils literal"><span class="pre">order_by</span></tt> method.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;headline&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The result above will be ordered by <tt class="docutils literal"><span class="pre">pub_date</span></tt> descending, then by
<tt class="docutils literal"><span class="pre">headline</span></tt> ascending. The negative sign in front of <tt class="docutils literal"><span class="pre">&quot;-pub_date&quot;</span></tt> indicates
<em>descending</em> order. Ascending order is implied. To order randomly, use <tt class="docutils literal"><span class="pre">&quot;?&quot;</span></tt>,
like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;?&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note: <tt class="docutils literal"><span class="pre">order_by('?')</span></tt> queries may be expensive and slow, depending on the
database backend you&#8217;re using.</p>
<p>To order by a field in a different model, use the same syntax as when you are
querying across model relations. That is, the name of the field, followed by a
double underscore (<tt class="docutils literal"><span class="pre">__</span></tt>), followed by the name of the field in the new model,
and so on for as many models as you want to join. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s">&#39;headline&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you try to order by a field that is a relation to another model, Django will
use the default ordering on the related model, or order by the related model&#8217;s
primary key if there is no <a class="reference internal" href="options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">Meta.ordering</span></tt></a> specified. For example, since the <tt class="docutils literal"><span class="pre">Blog</span></tt>
model has no default ordering specified:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>...is identical to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog__id&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <tt class="docutils literal"><span class="pre">Blog</span></tt> had <tt class="docutils literal"><span class="pre">ordering</span> <span class="pre">=</span> <span class="pre">['name']</span></tt>, then the first queryset would be
identical to:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog__name&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<span class="title">New in Django 1.7:</span> <p>Note that it is also possible to order a queryset by a related field,
without incurring the cost of a JOIN, by referring to the <tt class="docutils literal"><span class="pre">_id</span></tt> of the
related field:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># No Join</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog_id&#39;</span><span class="p">)</span>

<span class="c"># Join</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog__id&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>Be cautious when ordering by fields in related models if you are also using
<a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><tt class="xref py py-meth docutils literal"><span class="pre">distinct()</span></tt></a>. See the note in <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><tt class="xref py py-meth docutils literal"><span class="pre">distinct()</span></tt></a> for an explanation of how
related model ordering can change the expected results.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>It is permissible to specify a multi-valued field to order the results by
(for example, a <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> field, or the
reverse relation of a <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> field).</p>
<p>Consider this case:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Event</span><span class="p">(</span><span class="n">Model</span><span class="p">):</span>
   <span class="n">parent</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="s">&#39;self&#39;</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&#39;children&#39;</span><span class="p">)</span>
   <span class="n">date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

<span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;children__date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, there could potentially be multiple ordering data for each <tt class="docutils literal"><span class="pre">Event</span></tt>;
each <tt class="docutils literal"><span class="pre">Event</span></tt> with multiple <tt class="docutils literal"><span class="pre">children</span></tt> will be returned multiple times
into the new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that <tt class="docutils literal"><span class="pre">order_by()</span></tt> creates. In other words,
using <tt class="docutils literal"><span class="pre">order_by()</span></tt> on the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> could return more items than you
were working on to begin with - which is probably neither expected nor
useful.</p>
<p class="last">Thus, take care when using multi-valued field to order the results. <strong>If</strong>
you can be sure that there will only be one ordering piece of data for each
of the items you&#8217;re ordering, this approach should not present problems. If
not, make sure the results are what you expect.</p>
</div>
<p>There&#8217;s no way to specify whether ordering should be case sensitive. With
respect to case-sensitivity, Django will order results however your database
backend normally orders them.</p>
<p>If you don&#8217;t want any ordering to be applied to a query, not even the default
ordering, call <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> with no parameters.</p>
<p>You can tell if a query is ordered or not by checking the
<a class="reference internal" href="#django.db.models.query.QuerySet.ordered" title="django.db.models.query.QuerySet.ordered"><tt class="xref py py-attr docutils literal"><span class="pre">QuerySet.ordered</span></tt></a> attribute, which will be <tt class="docutils literal"><span class="pre">True</span></tt> if the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> has been ordered in any way.</p>
<p>Each <tt class="docutils literal"><span class="pre">order_by()</span></tt> call will clear any previous ordering. For example, this
query will be ordered by <tt class="docutils literal"><span class="pre">pub_date</span></tt> and not <tt class="docutils literal"><span class="pre">headline</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;headline&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Ordering is not a free operation. Each field you add to the ordering
incurs a cost to your database. Each foreign key you add will
implicitly include all of its default orderings as well.</p>
</div>
</div>
<div class="section" id="s-reverse">
<span id="reverse"></span><h4>reverse<a class="headerlink" href="#reverse" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.reverse">
<tt class="descname">reverse</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.reverse" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Use the <tt class="docutils literal"><span class="pre">reverse()</span></tt> method to reverse the order in which a queryset&#8217;s
elements are returned. Calling <tt class="docutils literal"><span class="pre">reverse()</span></tt> a second time restores the
ordering back to the normal direction.</p>
<p>To retrieve the &#8220;last&#8221; five items in a queryset, you could do this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">my_queryset</span><span class="o">.</span><span class="n">reverse</span><span class="p">()[:</span><span class="mi">5</span><span class="p">]</span>
</pre></div>
</div>
<p>Note that this is not quite the same as slicing from the end of a sequence in
Python. The above example will return the last item first, then the
penultimate item and so on. If we had a Python sequence and looked at
<tt class="docutils literal"><span class="pre">seq[-5:]</span></tt>, we would see the fifth-last item first. Django doesn&#8217;t support
that mode of access (slicing from the end), because it&#8217;s not possible to do it
efficiently in SQL.</p>
<p>Also, note that <tt class="docutils literal"><span class="pre">reverse()</span></tt> should generally only be called on a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>
which has a defined ordering (e.g., when querying against a model which defines
a default ordering, or when using <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a>). If no such ordering is
defined for a given <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, calling <tt class="docutils literal"><span class="pre">reverse()</span></tt> on it has no real
effect (the ordering was undefined prior to calling <tt class="docutils literal"><span class="pre">reverse()</span></tt>, and will
remain undefined afterward).</p>
</div>
<div class="section" id="s-distinct">
<span id="distinct"></span><h4>distinct<a class="headerlink" href="#distinct" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.distinct">
<tt class="descname">distinct</tt>(<span class="optional">[</span><em>*fields</em><span class="optional">]</span>)<a class="headerlink" href="#django.db.models.query.QuerySet.distinct" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a new <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that uses <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></tt> in its SQL query. This
eliminates duplicate rows from the query results.</p>
<p>By default, a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> will not eliminate duplicate rows. In practice, this
is rarely a problem, because simple queries such as <tt class="docutils literal"><span class="pre">Blog.objects.all()</span></tt>
don&#8217;t introduce the possibility of duplicate result rows. However, if your
query spans multiple tables, it&#8217;s possible to get duplicate results when a
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> is evaluated. That&#8217;s when you&#8217;d use <tt class="docutils literal"><span class="pre">distinct()</span></tt>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Any fields used in an <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> call are included in the SQL
<tt class="docutils literal"><span class="pre">SELECT</span></tt> columns. This can sometimes lead to unexpected results when used
in conjunction with <tt class="docutils literal"><span class="pre">distinct()</span></tt>. If you order by fields from a related
model, those fields will be added to the selected columns and they may make
otherwise duplicate rows appear to be distinct. Since the extra columns
don&#8217;t appear in the returned results (they are only there to support
ordering), it sometimes looks like non-distinct results are being returned.</p>
<p>Similarly, if you use a <a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt></a> query to restrict the columns
selected, the columns used in any <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> (or default model
ordering) will still be involved and may affect uniqueness of the results.</p>
<p class="last">The moral here is that if you are using <tt class="docutils literal"><span class="pre">distinct()</span></tt> be careful about
ordering by related models. Similarly, when using <tt class="docutils literal"><span class="pre">distinct()</span></tt> and
<a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt></a> together, be careful when ordering by fields not in the
<a class="reference internal" href="#django.db.models.query.QuerySet.values" title="django.db.models.query.QuerySet.values"><tt class="xref py py-meth docutils literal"><span class="pre">values()</span></tt></a> call.</p>
</div>
<p>On PostgreSQL only, you can pass positional arguments (<tt class="docutils literal"><span class="pre">*fields</span></tt>) in order to
specify the names of fields to which the <tt class="docutils literal"><span class="pre">DISTINCT</span></tt> should apply. This
translates to a <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span> <span class="pre">ON</span></tt> SQL query. Here&#8217;s the difference. For a
normal <tt class="docutils literal"><span class="pre">distinct()</span></tt> call, the database compares <em>each</em> field in each row when
determining which rows are distinct. For a <tt class="docutils literal"><span class="pre">distinct()</span></tt> call with specified
field names, the database will only compare the specified field names.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>When you specify field names, you <em>must</em> provide an <tt class="docutils literal"><span class="pre">order_by()</span></tt> in the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>, and the fields in <tt class="docutils literal"><span class="pre">order_by()</span></tt> must start with the fields in
<tt class="docutils literal"><span class="pre">distinct()</span></tt>, in the same order.</p>
<p class="last">For example, <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span> <span class="pre">ON</span> <span class="pre">(a)</span></tt> gives you the first row for each
value in column <tt class="docutils literal"><span class="pre">a</span></tt>. If you don&#8217;t specify an order, you&#8217;ll get some
arbitrary row.</p>
</div>
<p>Examples (those after the first will only work on PostgreSQL):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">distinct</span><span class="p">()</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;author&#39;</span><span class="p">,</span> <span class="s">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;author&#39;</span><span class="p">,</span> <span class="s">&#39;pub_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s">&#39;mod_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;blog__name&#39;</span><span class="p">,</span> <span class="s">&#39;mod_date&#39;</span><span class="p">)</span>
<span class="go">[...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;author&#39;</span><span class="p">,</span> <span class="s">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;author&#39;</span><span class="p">)</span>
<span class="go">[...]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Keep in mind that <a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> uses any default related model ordering
that has been defined. You might have to explicitly order by the relation
<tt class="docutils literal"><span class="pre">_id</span></tt> or referenced field to make sure the <tt class="docutils literal"><span class="pre">DISTINCT</span> <span class="pre">ON</span></tt> expressions
match those at the beginning of the <tt class="docutils literal"><span class="pre">ORDER</span> <span class="pre">BY</span></tt> clause. For example, if
the <tt class="docutils literal"><span class="pre">Blog</span></tt> model defined an <a class="reference internal" href="options.html#django.db.models.Options.ordering" title="django.db.models.Options.ordering"><tt class="xref py py-attr docutils literal"><span class="pre">ordering</span></tt></a> by
<tt class="docutils literal"><span class="pre">name</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">distinct</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">...wouldn&#8217;t work because the query would be ordered by <tt class="docutils literal"><span class="pre">blog__name</span></tt> thus
mismatching the <tt class="docutils literal"><span class="pre">DISTINCT</span> <span class="pre">ON</span></tt> expression. You&#8217;d have to explicitly order
by the relation <cite>_id</cite> field (<tt class="docutils literal"><span class="pre">blog_id</span></tt> in this case) or the referenced
one (<tt class="docutils literal"><span class="pre">blog__pk</span></tt>) to make sure both expressions match.</p>
</div>
</div>
<div class="section" id="s-values">
<span id="values"></span><h4>values<a class="headerlink" href="#values" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.values">
<tt class="descname">values</tt>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.values" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <tt class="docutils literal"><span class="pre">ValuesQuerySet</span></tt> — a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> subclass that returns
dictionaries when used as an iterable, rather than model-instance objects.</p>
<p>Each of those dictionaries represents an object, with the keys corresponding to
the attribute names of model objects.</p>
<p>This example compares the dictionaries of <tt class="docutils literal"><span class="pre">values()</span></tt> with the normal model
objects:</p>
<div class="highlight-python"><div class="highlight"><pre># This list contains a Blog object.
&gt;&gt;&gt; Blog.objects.filter(name__startswith=&#39;Beatles&#39;)
[&lt;Blog: Beatles Blog&gt;]

# This list contains a dictionary.
&gt;&gt;&gt; Blog.objects.filter(name__startswith=&#39;Beatles&#39;).values()
[{&#39;id&#39;: 1, &#39;name&#39;: &#39;Beatles Blog&#39;, &#39;tagline&#39;: &#39;All the latest Beatles news.&#39;}]
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">values()</span></tt> method takes optional positional arguments, <tt class="docutils literal"><span class="pre">*fields</span></tt>, which
specify field names to which the <tt class="docutils literal"><span class="pre">SELECT</span></tt> should be limited. If you specify
the fields, each dictionary will contain only the field keys/values for the
fields you specify. If you don&#8217;t specify the fields, each dictionary will
contain a key and value for every field in the database table.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="go">[{&#39;id&#39;: 1, &#39;name&#39;: &#39;Beatles Blog&#39;, &#39;tagline&#39;: &#39;All the latest Beatles news.&#39;}],</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">,</span> <span class="s">&#39;name&#39;</span><span class="p">)</span>
<span class="go">[{&#39;id&#39;: 1, &#39;name&#39;: &#39;Beatles Blog&#39;}]</span>
</pre></div>
</div>
<p>A few subtleties that are worth mentioning:</p>
<ul>
<li><p class="first">If you have a field called <tt class="docutils literal"><span class="pre">foo</span></tt> that is a
<a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>, the default <tt class="docutils literal"><span class="pre">values()</span></tt> call
will return a dictionary key called <tt class="docutils literal"><span class="pre">foo_id</span></tt>, since this is the name
of the hidden model attribute that stores the actual value (the <tt class="docutils literal"><span class="pre">foo</span></tt>
attribute refers to the related model). When you are calling
<tt class="docutils literal"><span class="pre">values()</span></tt> and passing in field names, you can pass in either <tt class="docutils literal"><span class="pre">foo</span></tt>
or <tt class="docutils literal"><span class="pre">foo_id</span></tt> and you will get back the same thing (the dictionary key
will match the field name you passed in).</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
<span class="go">[{&#39;blog_id&#39;: 1, &#39;headline&#39;: u&#39;First Entry&#39;, ...}, ...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span>
<span class="go">[{&#39;blog&#39;: 1}, ...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;blog_id&#39;</span><span class="p">)</span>
<span class="go">[{&#39;blog_id&#39;: 1}, ...]</span>
</pre></div>
</div>
</li>
<li><p class="first">When using <tt class="docutils literal"><span class="pre">values()</span></tt> together with <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><tt class="xref py py-meth docutils literal"><span class="pre">distinct()</span></tt></a>, be aware that
ordering can affect the results. See the note in <a class="reference internal" href="#django.db.models.query.QuerySet.distinct" title="django.db.models.query.QuerySet.distinct"><tt class="xref py py-meth docutils literal"><span class="pre">distinct()</span></tt></a> for
details.</p>
</li>
<li><p class="first">If you use a <tt class="docutils literal"><span class="pre">values()</span></tt> clause after an <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><tt class="xref py py-meth docutils literal"><span class="pre">extra()</span></tt></a> call,
any fields defined by a <tt class="docutils literal"><span class="pre">select</span></tt> argument in the <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><tt class="xref py py-meth docutils literal"><span class="pre">extra()</span></tt></a> must
be explicitly included in the <tt class="docutils literal"><span class="pre">values()</span></tt> call. Any <a class="reference internal" href="#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><tt class="xref py py-meth docutils literal"><span class="pre">extra()</span></tt></a> call
made after a <tt class="docutils literal"><span class="pre">values()</span></tt> call will have its extra selected fields
ignored.</p>
</li>
<li><p class="first">Calling <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><tt class="xref py py-meth docutils literal"><span class="pre">only()</span></tt></a> and <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">defer()</span></tt></a> after <tt class="docutils literal"><span class="pre">values()</span></tt> doesn&#8217;t make
sense, so doing so will raise a <tt class="docutils literal"><span class="pre">NotImplementedError</span></tt>.</p>
</li>
</ul>
<div class="versionadded">
<span class="title">New in Django 1.7:</span> <p>The last point above is new. Previously, calling <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><tt class="xref py py-meth docutils literal"><span class="pre">only()</span></tt></a> and
<a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">defer()</span></tt></a> after <tt class="docutils literal"><span class="pre">values()</span></tt> was allowed, but it either crashed or
returned incorrect results.</p>
</div>
<p>A <tt class="docutils literal"><span class="pre">ValuesQuerySet</span></tt> is useful when you know you&#8217;re only going to need values
from a small number of the available fields and you won&#8217;t need the
functionality of a model instance object. It&#8217;s more efficient to select only
the fields you need to use.</p>
<p>Finally, note that a <tt class="docutils literal"><span class="pre">ValuesQuerySet</span></tt> is a subclass of <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and it
implements most of the same methods. You can call <tt class="docutils literal"><span class="pre">filter()</span></tt> on it,
<tt class="docutils literal"><span class="pre">order_by()</span></tt>, etc. That means that these two calls are identical:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">()</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">)</span>
<span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">()</span>
</pre></div>
</div>
<p>The people who made Django prefer to put all the SQL-affecting methods first,
followed (optionally) by any output-affecting methods (such as <tt class="docutils literal"><span class="pre">values()</span></tt>),
but it doesn&#8217;t really matter. This is your chance to really flaunt your
individualism.</p>
<p>You can also refer to fields on related models with reverse relations through
<tt class="docutils literal"><span class="pre">OneToOneField</span></tt>, <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> and <tt class="docutils literal"><span class="pre">ManyToManyField</span></tt> attributes:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">,</span> <span class="s">&#39;entry__headline&#39;</span><span class="p">)</span>
<span class="p">[{</span><span class="s">&#39;name&#39;</span><span class="p">:</span> <span class="s">&#39;My blog&#39;</span><span class="p">,</span> <span class="s">&#39;entry__headline&#39;</span><span class="p">:</span> <span class="s">&#39;An entry&#39;</span><span class="p">},</span>
     <span class="p">{</span><span class="s">&#39;name&#39;</span><span class="p">:</span> <span class="s">&#39;My blog&#39;</span><span class="p">,</span> <span class="s">&#39;entry__headline&#39;</span><span class="p">:</span> <span class="s">&#39;Another entry&#39;</span><span class="p">},</span> <span class="o">...</span><span class="p">]</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Because <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a> attributes and reverse
relations can have multiple related rows, including these can have a
multiplier effect on the size of your result set. This will be especially
pronounced if you include multiple such fields in your <tt class="docutils literal"><span class="pre">values()</span></tt> query,
in which case all possible combinations will be returned.</p>
</div>
</div>
<div class="section" id="s-values-list">
<span id="values-list"></span><h4>values_list<a class="headerlink" href="#values-list" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.values_list">
<tt class="descname">values_list</tt>(<em>*fields</em>, <em>flat=False</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.values_list" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This is similar to <tt class="docutils literal"><span class="pre">values()</span></tt> except that instead of returning dictionaries,
it returns tuples when iterated over. Each tuple contains the value from the
respective field passed into the <tt class="docutils literal"><span class="pre">values_list()</span></tt> call — so the first item is
the first field, etc. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">,</span> <span class="s">&#39;headline&#39;</span><span class="p">)</span>
<span class="go">[(1, u&#39;First entry&#39;), ...]</span>
</pre></div>
</div>
<p>If you only pass in a single field, you can also pass in the <tt class="docutils literal"><span class="pre">flat</span></tt>
parameter. If <tt class="docutils literal"><span class="pre">True</span></tt>, this will mean the returned results are single values,
rather than one-tuples. An example should make the difference clearer:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">)</span>
<span class="go">[(1,), (2,), (3,), ...]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">)</span>
<span class="go">[1, 2, 3, ...]</span>
</pre></div>
</div>
<p>It is an error to pass in <tt class="docutils literal"><span class="pre">flat</span></tt> when there is more than one field.</p>
<p>If you don&#8217;t pass any values to <tt class="docutils literal"><span class="pre">values_list()</span></tt>, it will return all the
fields in the model, in the order they were declared.</p>
<p>Note that this method returns a <tt class="docutils literal"><span class="pre">ValuesListQuerySet</span></tt>. This class behaves
like a list. Most of the time this is enough, but if you require an actual
Python list object, you can simply call <tt class="docutils literal"><span class="pre">list()</span></tt> on it, which will evaluate
the queryset.</p>
</div>
<div class="section" id="s-dates">
<span id="dates"></span><h4>dates<a class="headerlink" href="#dates" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.dates">
<tt class="descname">dates</tt>(<em>field</em>, <em>kind</em>, <em>order='ASC'</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.dates" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <tt class="docutils literal"><span class="pre">DateQuerySet</span></tt> — a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that evaluates to a list of
<a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.date" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime.date</span></tt></a> objects representing all available dates of a
particular kind within the contents of the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p><tt class="docutils literal"><span class="pre">dates</span></tt> used to return a list of <a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime.datetime</span></tt></a> objects.</p>
</div>
<p><tt class="docutils literal"><span class="pre">field</span></tt> should be the name of a <tt class="docutils literal"><span class="pre">DateField</span></tt> of your model.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p><tt class="docutils literal"><span class="pre">dates</span></tt> used to accept operating on a <tt class="docutils literal"><span class="pre">DateTimeField</span></tt>.</p>
</div>
<p><tt class="docutils literal"><span class="pre">kind</span></tt> should be either <tt class="docutils literal"><span class="pre">&quot;year&quot;</span></tt>, <tt class="docutils literal"><span class="pre">&quot;month&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;day&quot;</span></tt>. Each
<tt class="docutils literal"><span class="pre">datetime.date</span></tt> object in the result list is &#8220;truncated&#8221; to the given
<tt class="docutils literal"><span class="pre">type</span></tt>.</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">&quot;year&quot;</span></tt> returns a list of all distinct year values for the field.</li>
<li><tt class="docutils literal"><span class="pre">&quot;month&quot;</span></tt> returns a list of all distinct year/month values for the
field.</li>
<li><tt class="docutils literal"><span class="pre">&quot;day&quot;</span></tt> returns a list of all distinct year/month/day values for the
field.</li>
</ul>
<p><tt class="docutils literal"><span class="pre">order</span></tt>, which defaults to <tt class="docutils literal"><span class="pre">'ASC'</span></tt>, should be either <tt class="docutils literal"><span class="pre">'ASC'</span></tt> or
<tt class="docutils literal"><span class="pre">'DESC'</span></tt>. This specifies how to order the results.</p>
<p>Examples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;year&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 1, 1)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;month&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;day&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;day&#39;</span><span class="p">,</span> <span class="n">order</span><span class="o">=</span><span class="s">&#39;DESC&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">dates</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">,</span> <span class="s">&#39;day&#39;</span><span class="p">)</span>
<span class="go">[datetime.date(2005, 3, 20)]</span>
</pre></div>
</div>
</div>
<div class="section" id="s-datetimes">
<span id="datetimes"></span><h4>datetimes<a class="headerlink" href="#datetimes" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<dl class="method">
<dt id="django.db.models.query.QuerySet.datetimes">
<tt class="descname">datetimes</tt>(<em>field_name</em>, <em>kind</em>, <em>order='ASC'</em>, <em>tzinfo=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.datetimes" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <tt class="docutils literal"><span class="pre">DateTimeQuerySet</span></tt> — a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that evaluates to a list of
<a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.datetime" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime.datetime</span></tt></a> objects representing all available dates of a
particular kind within the contents of the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">field_name</span></tt> should be the name of a <tt class="docutils literal"><span class="pre">DateTimeField</span></tt> of your model.</p>
<p><tt class="docutils literal"><span class="pre">kind</span></tt> should be either <tt class="docutils literal"><span class="pre">&quot;year&quot;</span></tt>, <tt class="docutils literal"><span class="pre">&quot;month&quot;</span></tt>, <tt class="docutils literal"><span class="pre">&quot;day&quot;</span></tt>, <tt class="docutils literal"><span class="pre">&quot;hour&quot;</span></tt>,
<tt class="docutils literal"><span class="pre">&quot;minute&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;second&quot;</span></tt>. Each <tt class="docutils literal"><span class="pre">datetime.datetime</span></tt> object in the result
list is &#8220;truncated&#8221; to the given <tt class="docutils literal"><span class="pre">type</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">order</span></tt>, which defaults to <tt class="docutils literal"><span class="pre">'ASC'</span></tt>, should be either <tt class="docutils literal"><span class="pre">'ASC'</span></tt> or
<tt class="docutils literal"><span class="pre">'DESC'</span></tt>. This specifies how to order the results.</p>
<p><tt class="docutils literal"><span class="pre">tzinfo</span></tt> defines the time zone to which datetimes are converted prior to
truncation. Indeed, a given datetime has different representations depending
on the time zone in use. This parameter must be a <a class="reference external" href="http://docs.python.org/3/library/datetime.html#datetime.tzinfo" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">datetime.tzinfo</span></tt></a>
object. If it&#8217;s <tt class="docutils literal"><span class="pre">None</span></tt>, Django uses the <a class="reference internal" href="../../topics/i18n/timezones.html#default-current-time-zone"><em>current time zone</em></a>. It has no effect when <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is
<tt class="docutils literal"><span class="pre">False</span></tt>.</p>
<div class="admonition note" id="database-time-zone-definitions">
<p class="first admonition-title">Note</p>
<p>This function performs time zone conversions directly in the database.
As a consequence, your database must be able to interpret the value of
<tt class="docutils literal"><span class="pre">tzinfo.tzname(None)</span></tt>. This translates into the following requirements:</p>
<ul class="last simple">
<li>SQLite: install <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> — conversions are actually performed in Python.</li>
<li>PostgreSQL: no requirements (see <a class="reference external" href="http://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-TIMEZONES">Time Zones</a>).</li>
<li>Oracle: no requirements (see <a class="reference external" href="http://docs.oracle.com/cd/B19306_01/server.102/b14225/ch4datetime.htm#i1006667">Choosing a Time Zone File</a>).</li>
<li>MySQL: install <a class="reference external" href="http://pytz.sourceforge.net/">pytz</a> and load the time zone tables with
<a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/mysql-tzinfo-to-sql.html">mysql_tzinfo_to_sql</a>.</li>
</ul>
</div>
</div>
<div class="section" id="s-none">
<span id="none"></span><h4>none<a class="headerlink" href="#none" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.none">
<tt class="descname">none</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.none" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Calling none() will create a queryset that never returns any objects and no
query will be executed when accessing the results. A qs.none() queryset
is an instance of <tt class="docutils literal"><span class="pre">EmptyQuerySet</span></tt>.</p>
<p>Examples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">none</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models.query</span> <span class="kn">import</span> <span class="n">EmptyQuerySet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">none</span><span class="p">(),</span> <span class="n">EmptyQuerySet</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="s-all">
<span id="all"></span><h4>all<a class="headerlink" href="#all" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.all">
<tt class="descname">all</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.all" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <em>copy</em> of the current <tt class="docutils literal"><span class="pre">QuerySet</span></tt> (or <tt class="docutils literal"><span class="pre">QuerySet</span></tt> subclass).  This
can be useful in situations where you might want to pass in either a model
manager or a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and do further filtering on the result. After calling
<tt class="docutils literal"><span class="pre">all()</span></tt> on either object, you&#8217;ll definitely have a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> to work with.</p>
<p>When a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is <a class="reference internal" href="#when-querysets-are-evaluated"><em>evaluated</em></a>, it
typically caches its results. If the data in the database might have changed
since a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> was evaluated, you can get updated results for the same
query by calling <tt class="docutils literal"><span class="pre">all()</span></tt> on a previously evaluated <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
</div>
<div class="section" id="s-select-related">
<span id="select-related"></span><h4>select_related<a class="headerlink" href="#select-related" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.select_related">
<tt class="descname">select_related</tt>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.select_related" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that will &#8220;follow&#8221; foreign-key relationships, selecting
additional related-object data when it executes its query. This is a
performance booster which results in a single more complex query but means
later use of foreign-key relationships won&#8217;t require database queries.</p>
<p>The following examples illustrate the difference between plain lookups and
<tt class="docutils literal"><span class="pre">select_related()</span></tt> lookups. Here&#8217;s standard lookup:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Hits the database.</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="c"># Hits the database again to get the related Blog object.</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>
</pre></div>
</div>
<p>And here&#8217;s <tt class="docutils literal"><span class="pre">select_related</span></tt> lookup:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Hits the database.</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="c"># Doesn&#39;t hit the database, because e.blog has been prepopulated</span>
<span class="c"># in the previous query.</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">e</span><span class="o">.</span><span class="n">blog</span>
</pre></div>
</div>
<p>You can use <tt class="docutils literal"><span class="pre">select_related()</span></tt> with any queryset of objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>

<span class="c"># Find all the blogs with entries scheduled to be published in the future.</span>
<span class="n">blogs</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>

<span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">):</span>
    <span class="c"># Without select_related(), this would make a database query for each</span>
    <span class="c"># loop iteration in order to fetch the related blog for each entry.</span>
    <span class="n">blogs</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>
</pre></div>
</div>
<p>The order of <tt class="docutils literal"><span class="pre">filter()</span></tt> and <tt class="docutils literal"><span class="pre">select_related()</span></tt> chaining isn&#8217;t important.
These querysets are equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;blog&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gt</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
<p>You can follow foreign keys in a similar way to querying them. If you have the
following models:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">City</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">hometown</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">City</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">)</span>
</pre></div>
</div>
<p>... then a call to <tt class="docutils literal"><span class="pre">Book.objects.select_related('author__hometown').get(id=4)</span></tt>
will cache the related <tt class="docutils literal"><span class="pre">Person</span></tt> <em>and</em> the related <tt class="docutils literal"><span class="pre">City</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">b</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;author__hometown&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">author</span>         <span class="c"># Doesn&#39;t hit the database.</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">hometown</span>       <span class="c"># Doesn&#39;t hit the database.</span>

<span class="n">b</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span> <span class="c"># No select_related() in this example.</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">author</span>         <span class="c"># Hits the database.</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">hometown</span>       <span class="c"># Hits the database.</span>
</pre></div>
</div>
<p>You can refer to any <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> or
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> relation in the list of fields
passed to <tt class="docutils literal"><span class="pre">select_related()</span></tt>.</p>
<p>You can also refer to the reverse direction of a
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> in the list of fields passed to
<tt class="docutils literal"><span class="pre">select_related</span></tt> — that is, you can traverse a
<a class="reference internal" href="fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> back to the object on which the field
is defined. Instead of specifying the field name, use the <a class="reference internal" href="fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><tt class="xref py py-attr docutils literal"><span class="pre">related_name</span></tt></a> for the field on the related object.</p>
<p>There may be some situations where you wish to call <tt class="docutils literal"><span class="pre">select_related()</span></tt> with a
lot of related objects, or where you don&#8217;t know all of the relations. In these
cases it is possible to call <tt class="docutils literal"><span class="pre">select_related()</span></tt> with no arguments. This will
follow all non-null foreign keys it can find - nullable foreign keys must be
specified. This is not recommended in most cases as it is likely to make the
underlying query more complex, and return more data, than is actually needed.</p>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>If you need to clear the list of related fields added by past calls of
<tt class="docutils literal"><span class="pre">select_related</span></tt> on a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>, you can pass <tt class="docutils literal"><span class="pre">None</span></tt> as a parameter:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">without_relations</span> <span class="o">=</span> <span class="n">queryset</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>Chaining <tt class="docutils literal"><span class="pre">select_related</span></tt> calls works in a similar way to other methods -
that is that <tt class="docutils literal"><span class="pre">select_related('foo',</span> <span class="pre">'bar')</span></tt> is equivalent to
<tt class="docutils literal"><span class="pre">select_related('foo').select_related('bar')</span></tt>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>Previously the latter would have been equivalent to
<tt class="docutils literal"><span class="pre">select_related('bar')</span></tt>.</p>
</div>
</div>
<div class="section" id="s-prefetch-related">
<span id="prefetch-related"></span><h4>prefetch_related<a class="headerlink" href="#prefetch-related" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.prefetch_related">
<tt class="descname">prefetch_related</tt>(<em>*lookups</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.prefetch_related" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that will automatically retrieve, in a single batch,
related objects for each of the specified lookups.</p>
<p>This has a similar purpose to <tt class="docutils literal"><span class="pre">select_related</span></tt>, in that both are designed to
stop the deluge of database queries that is caused by accessing related objects,
but the strategy is quite different.</p>
<p><tt class="docutils literal"><span class="pre">select_related</span></tt> works by creating an SQL join and including the fields of the
related object in the <tt class="docutils literal"><span class="pre">SELECT</span></tt> statement. For this reason, <tt class="docutils literal"><span class="pre">select_related</span></tt>
gets the related objects in the same database query. However, to avoid the much
larger result set that would result from joining across a &#8216;many&#8217; relationship,
<tt class="docutils literal"><span class="pre">select_related</span></tt> is limited to single-valued relationships - foreign key and
one-to-one.</p>
<p><tt class="docutils literal"><span class="pre">prefetch_related</span></tt>, on the other hand, does a separate lookup for each
relationship, and does the &#8216;joining&#8217; in Python. This allows it to prefetch
many-to-many and many-to-one objects, which cannot be done using
<tt class="docutils literal"><span class="pre">select_related</span></tt>, in addition to the foreign key and one-to-one relationships
that are supported by <tt class="docutils literal"><span class="pre">select_related</span></tt>. It also supports prefetching of
<a class="reference internal" href="../contrib/contenttypes.html#django.contrib.contenttypes.fields.GenericRelation" title="django.contrib.contenttypes.fields.GenericRelation"><tt class="xref py py-class docutils literal"><span class="pre">GenericRelation</span></tt></a> and
<a class="reference internal" href="../contrib/contenttypes.html#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">GenericForeignKey</span></tt></a>.</p>
<p>For example, suppose you have these models:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Topping</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Pizza</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
    <span class="n">toppings</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Topping</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="s">&quot;</span><span class="si">%s</span><span class="s"> (</span><span class="si">%s</span><span class="s">)&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="s">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">topping</span><span class="o">.</span><span class="n">name</span>
                                                  <span class="k">for</span> <span class="n">topping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">toppings</span><span class="o">.</span><span class="n">all</span><span class="p">()]))</span>
</pre></div>
</div>
<p>and run:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&quot;Hawaiian (ham, pineapple)&quot;, &quot;Seafood (prawns, smoked salmon)&quot;...</span>
</pre></div>
</div>
<p>The problem with this is that every time <tt class="docutils literal"><span class="pre">Pizza.__str__()</span></tt> asks for
<tt class="docutils literal"><span class="pre">self.toppings.all()</span></tt> it has to query the database, so
<tt class="docutils literal"><span class="pre">Pizza.objects.all()</span></tt> will run a query on the Toppings table for <strong>every</strong>
item in the Pizza <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p>We can reduce to just two queries using <tt class="docutils literal"><span class="pre">prefetch_related</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This implies a <tt class="docutils literal"><span class="pre">self.toppings.all()</span></tt> for each <tt class="docutils literal"><span class="pre">Pizza</span></tt>; now each time
<tt class="docutils literal"><span class="pre">self.toppings.all()</span></tt> is called, instead of having to go to the database for
the items, it will find them in a prefetched <tt class="docutils literal"><span class="pre">QuerySet</span></tt> cache that was
populated in a single query.</p>
<p>That is, all the relevant toppings will have been fetched in a single query,
and used to make <tt class="docutils literal"><span class="pre">QuerySets</span></tt> that have a pre-filled cache of the relevant
results; these <tt class="docutils literal"><span class="pre">QuerySets</span></tt> are then used in the <tt class="docutils literal"><span class="pre">self.toppings.all()</span></tt> calls.</p>
<p>The additional queries in <tt class="docutils literal"><span class="pre">prefetch_related()</span></tt> are executed after the
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> has begun to be evaluated and the primary query has been executed.</p>
<p>Note that the result cache of the primary <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and all specified related
objects will then be fully loaded into memory. This changes the typical
behavior of <tt class="docutils literal"><span class="pre">QuerySets</span></tt>, which normally try to avoid loading all objects into
memory before they are needed, even after a query has been executed in the
database.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Remember that, as always with <tt class="docutils literal"><span class="pre">QuerySets</span></tt>, any subsequent chained methods
which imply a different database query will ignore previously cached
results, and retrieve data using a fresh database query. So, if you write
the following:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;toppings&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">list</span><span class="p">(</span><span class="n">pizza</span><span class="o">.</span><span class="n">toppings</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">spicy</span><span class="o">=</span><span class="bp">True</span><span class="p">))</span> <span class="k">for</span> <span class="n">pizza</span> <span class="ow">in</span> <span class="n">pizzas</span><span class="p">]</span>
</pre></div>
</div>
<p class="last">...then the fact that <tt class="docutils literal"><span class="pre">pizza.toppings.all()</span></tt> has been prefetched will not
help you. The <tt class="docutils literal"><span class="pre">prefetch_related('toppings')</span></tt> implied
<tt class="docutils literal"><span class="pre">pizza.toppings.all()</span></tt>, but <tt class="docutils literal"><span class="pre">pizza.toppings.filter()</span></tt> is a new and
different query. The prefetched cache can&#8217;t help here; in fact it hurts
performance, since you have done a database query that you haven&#8217;t used. So
use this feature with caution!</p>
</div>
<p>You can also use the normal join syntax to do related fields of related
fields. Suppose we have an additional model to the example above:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">pizzas</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToMany</span><span class="p">(</span><span class="n">Pizza</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&#39;restaurants&#39;</span><span class="p">)</span>
    <span class="n">best_pizza</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Pizza</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">&#39;championed_by&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The following are all legal:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;pizzas__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will prefetch all pizzas belonging to restaurants, and all toppings
belonging to those pizzas. This will result in a total of 3 database queries -
one for the restaurants, one for the pizzas, and one for the toppings.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;best_pizza__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will fetch the best pizza and all the toppings for the best pizza for each
restaurant. This will be done in 3 database queries - one for the restaurants,
one for the &#8216;best pizzas&#8217;, and one for one for the toppings.</p>
<p>Of course, the <tt class="docutils literal"><span class="pre">best_pizza</span></tt> relationship could also be fetched using
<tt class="docutils literal"><span class="pre">select_related</span></tt> to reduce the query count to 2:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;best_pizza&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;best_pizza__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since the prefetch is executed after the main query (which includes the joins
needed by <tt class="docutils literal"><span class="pre">select_related</span></tt>), it is able to detect that the <tt class="docutils literal"><span class="pre">best_pizza</span></tt>
objects have already been fetched, and it will skip fetching them again.</p>
<p>Chaining <tt class="docutils literal"><span class="pre">prefetch_related</span></tt> calls will accumulate the lookups that are
prefetched. To clear any <tt class="docutils literal"><span class="pre">prefetch_related</span></tt> behavior, pass <tt class="docutils literal"><span class="pre">None</span></tt> as a
parameter:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">non_prefetched</span> <span class="o">=</span> <span class="n">qs</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>One difference to note when using <tt class="docutils literal"><span class="pre">prefetch_related</span></tt> is that objects created
by a query can be shared between the different objects that they are related to
i.e. a single Python model instance can appear at more than one point in the
tree of objects that are returned. This will normally happen with foreign key
relationships. Typically this behavior will not be a problem, and will in fact
save both memory and CPU time.</p>
<p>While <tt class="docutils literal"><span class="pre">prefetch_related</span></tt> supports prefetching <tt class="docutils literal"><span class="pre">GenericForeignKey</span></tt>
relationships, the number of queries will depend on the data. Since a
<tt class="docutils literal"><span class="pre">GenericForeignKey</span></tt> can reference data in multiple tables, one query per table
referenced is needed, rather than one query for all the items. There could be
additional queries on the <tt class="docutils literal"><span class="pre">ContentType</span></tt> table if the relevant rows have not
already been fetched.</p>
<p><tt class="docutils literal"><span class="pre">prefetch_related</span></tt> in most cases will be implemented using an SQL query that
uses the &#8216;IN&#8217; operator. This means that for a large <tt class="docutils literal"><span class="pre">QuerySet</span></tt> a large &#8216;IN&#8217; clause
could be generated, which, depending on the database, might have performance
problems of its own when it comes to parsing or executing the SQL query. Always
profile for your use case!</p>
<p>Note that if you use <tt class="docutils literal"><span class="pre">iterator()</span></tt> to run the query, <tt class="docutils literal"><span class="pre">prefetch_related()</span></tt>
calls will be ignored since these two optimizations do not make sense together.</p>
<div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>You can use the <a class="reference internal" href="queries.html#django.db.models.Prefetch" title="django.db.models.Prefetch"><tt class="xref py py-class docutils literal"><span class="pre">Prefetch</span></tt></a> object to further control
the prefetch operation.</p>
<p>In its simplest form <tt class="docutils literal"><span class="pre">Prefetch</span></tt> is equivalent to the traditional string based
lookups:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span><span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas__toppings&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>You can provide a custom queryset with the optional <tt class="docutils literal"><span class="pre">queryset</span></tt> argument.
This can be used to change the default ordering of the queryset:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Toppings</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">)))</span>
</pre></div>
</div>
<p>Or to call <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><tt class="xref py py-meth docutils literal"><span class="pre">select_related()</span></tt></a> when
applicable to reduce the number of queries even further:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;restaurants&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">(</span><span class="s">&#39;best_pizza&#39;</span><span class="p">)))</span>
</pre></div>
</div>
<p>You can also assign the prefetched result to a custom attribute with the optional
<tt class="docutils literal"><span class="pre">to_attr</span></tt> argument. The result will be stored directly in a list.</p>
<p>This allows prefetching the same relation multiple times with a different
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>; for instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s">&#39;menu&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">vegetarian_pizzas</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s">&#39;vegetarian_menu&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>Lookups created with custom <tt class="docutils literal"><span class="pre">to_attr</span></tt> can still be traversed as usual by other
lookups:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">vegetarian_pizzas</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s">&#39;vegetarian_menu&#39;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="s">&#39;vegetarian_menu__toppings&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Using <tt class="docutils literal"><span class="pre">to_attr</span></tt> is recommended when filtering down the prefetch result as it is
less ambiguous than storing a filtered result in the related manager&#8217;s cache:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">vegetarian</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Recommended:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s">&#39;vegetarian_pizzas&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">restaurants</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">vegetarian_pizzas</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Not recommended:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vegetarian_pizzas</span> <span class="o">=</span> <span class="n">restaurants</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">pizzas</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
<p>Custom prefetching also works with single related relations like
forward <tt class="docutils literal"><span class="pre">ForeignKey</span></tt> or <tt class="docutils literal"><span class="pre">OneToOneField</span></tt>. Generally you&#8217;ll want to use
<a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><tt class="xref py py-meth docutils literal"><span class="pre">select_related()</span></tt></a> for these relations, but there are a number of cases
where prefetching with a custom <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is useful:</p>
<ul>
<li><p class="first">You want to use a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> that performs further prefetching
on related models.</p>
</li>
<li><p class="first">You want to prefetch only a subset of the related objects.</p>
</li>
<li><p class="first">You want to use performance optimization techniques like
<a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">deferred</span> <span class="pre">fields</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">restaurants</span> <span class="o">=</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">prefetch_related</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;best_pizza&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">queryset</span><span class="p">))</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The ordering of lookups matters.</p>
<p>Take the following examples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="s">&#39;pizzas&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This works even though it&#8217;s unordered because <tt class="docutils literal"><span class="pre">'pizzas__toppings'</span></tt>
already contains all the needed information, therefore the second argument
<tt class="docutils literal"><span class="pre">'pizzas'</span></tt> is actually redundant.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;pizzas__toppings&#39;</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">queryset</span><span class="o">=</span><span class="n">Pizza</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()))</span>
</pre></div>
</div>
<p>This will raise a <tt class="docutils literal"><span class="pre">ValueError</span></tt> because of the attempt to redefine the
queryset of a previously seen lookup. Note that an implicit queryset was
created to traverse <tt class="docutils literal"><span class="pre">'pizzas'</span></tt> as part of the <tt class="docutils literal"><span class="pre">'pizzas__toppings'</span></tt>
lookup.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">prefetch_related</span><span class="p">(</span><span class="s">&#39;pizza_list__toppings&#39;</span><span class="p">,</span> <span class="n">Prefetch</span><span class="p">(</span><span class="s">&#39;pizzas&#39;</span><span class="p">,</span> <span class="n">to_attr</span><span class="o">=</span><span class="s">&#39;pizza_list&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>This will trigger an <tt class="docutils literal"><span class="pre">AttributeError</span></tt> because <tt class="docutils literal"><span class="pre">'pizza_list'</span></tt> doesn&#8217;t exist yet
when <tt class="docutils literal"><span class="pre">'pizza_list__toppings'</span></tt> is being processed.</p>
<p class="last">This consideration is not limited to the use of <tt class="docutils literal"><span class="pre">Prefetch</span></tt> objects. Some
advanced techniques may require that the lookups be performed in a
specific order to avoid creating extra queries; therefore it&#8217;s recommended
to always carefully order <tt class="docutils literal"><span class="pre">prefetch_related</span></tt> arguments.</p>
</div>
</div>
<div class="section" id="s-extra">
<span id="extra"></span><h4>extra<a class="headerlink" href="#extra" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.extra">
<tt class="descname">extra</tt>(<em>select=None</em>, <em>where=None</em>, <em>params=None</em>, <em>tables=None</em>, <em>order_by=None</em>, <em>select_params=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.extra" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Sometimes, the Django query syntax by itself can&#8217;t easily express a complex
<tt class="docutils literal"><span class="pre">WHERE</span></tt> clause. For these edge cases, Django provides the <tt class="docutils literal"><span class="pre">extra()</span></tt>
<tt class="docutils literal"><span class="pre">QuerySet</span></tt> modifier — a hook for injecting specific clauses into the SQL
generated by a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">You should be very careful whenever you use <tt class="docutils literal"><span class="pre">extra()</span></tt>. Every time you use
it, you should escape any parameters that the user can control by using
<tt class="docutils literal"><span class="pre">params</span></tt> in order to protect against SQL injection attacks . Please
read more about <a class="reference internal" href="../../topics/security.html#sql-injection-protection"><em>SQL injection protection</em></a>.</p>
</div>
<p>By definition, these extra lookups may not be portable to different database
engines (because you&#8217;re explicitly writing SQL code) and violate the DRY
principle, so you should avoid them if possible.</p>
<p>Specify one or more of <tt class="docutils literal"><span class="pre">params</span></tt>, <tt class="docutils literal"><span class="pre">select</span></tt>, <tt class="docutils literal"><span class="pre">where</span></tt> or <tt class="docutils literal"><span class="pre">tables</span></tt>. None
of the arguments is required, but you should use at least one of them.</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">select</span></tt></p>
<p>The <tt class="docutils literal"><span class="pre">select</span></tt> argument lets you put extra fields in the <tt class="docutils literal"><span class="pre">SELECT</span></tt>
clause.  It should be a dictionary mapping attribute names to SQL
clauses to use to calculate that attribute.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">select</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;is_recent&#39;</span><span class="p">:</span> <span class="s">&quot;pub_date &gt; &#39;2006-01-01&#39;&quot;</span><span class="p">})</span>
</pre></div>
</div>
<p>As a result, each <tt class="docutils literal"><span class="pre">Entry</span></tt> object will have an extra attribute,
<tt class="docutils literal"><span class="pre">is_recent</span></tt>, a boolean representing whether the entry&#8217;s <tt class="docutils literal"><span class="pre">pub_date</span></tt>
is greater than Jan. 1, 2006.</p>
<p>Django inserts the given SQL snippet directly into the <tt class="docutils literal"><span class="pre">SELECT</span></tt>
statement, so the resulting SQL of the above example would be something
like:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT blog_entry.*, (pub_date &gt; &#39;2006-01-01&#39;) AS is_recent
FROM blog_entry;
</pre></div>
</div>
<p>The next example is more advanced; it does a subquery to give each
resulting <tt class="docutils literal"><span class="pre">Blog</span></tt> object an <tt class="docutils literal"><span class="pre">entry_count</span></tt> attribute, an integer count
of associated <tt class="docutils literal"><span class="pre">Entry</span></tt> objects:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span>
    <span class="n">select</span><span class="o">=</span><span class="p">{</span>
        <span class="s">&#39;entry_count&#39;</span><span class="p">:</span> <span class="s">&#39;SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id&#39;</span>
    <span class="p">},</span>
<span class="p">)</span>
</pre></div>
</div>
<p>In this particular case, we&#8217;re exploiting the fact that the query will
already contain the <tt class="docutils literal"><span class="pre">blog_blog</span></tt> table in its <tt class="docutils literal"><span class="pre">FROM</span></tt> clause.</p>
<p>The resulting SQL of the above example would be:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count
FROM blog_blog;
</pre></div>
</div>
<p>Note that the parentheses required by most database engines around
subqueries are not required in Django&#8217;s <tt class="docutils literal"><span class="pre">select</span></tt> clauses. Also note
that some database backends, such as some MySQL versions, don&#8217;t support
subqueries.</p>
<p>In some rare cases, you might wish to pass parameters to the SQL
fragments in <tt class="docutils literal"><span class="pre">extra(select=...)</span></tt>. For this purpose, use the
<tt class="docutils literal"><span class="pre">select_params</span></tt> parameter. Since <tt class="docutils literal"><span class="pre">select_params</span></tt> is a sequence and
the <tt class="docutils literal"><span class="pre">select</span></tt> attribute is a dictionary, some care is required so that
the parameters are matched up correctly with the extra select pieces.
In this situation, you should use a <a class="reference external" href="http://docs.python.org/3/library/collections.html#collections.OrderedDict" title="(in Python v3.4)"><tt class="xref py py-class docutils literal"><span class="pre">collections.OrderedDict</span></tt></a> for
the <tt class="docutils literal"><span class="pre">select</span></tt> value, not just a normal Python dictionary.</p>
<p>This will work, for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span>
    <span class="n">select</span><span class="o">=</span><span class="n">OrderedDict</span><span class="p">([(</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s">&#39;b&#39;</span><span class="p">,</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">&#39;</span><span class="p">)]),</span>
    <span class="n">select_params</span><span class="o">=</span><span class="p">(</span><span class="s">&#39;one&#39;</span><span class="p">,</span> <span class="s">&#39;two&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>The only thing to be careful about when using select parameters in
<tt class="docutils literal"><span class="pre">extra()</span></tt> is to avoid using the substring <tt class="docutils literal"><span class="pre">&quot;%%s&quot;</span></tt> (that&#8217;s <em>two</em>
percent characters before the <tt class="docutils literal"><span class="pre">s</span></tt>) in the select strings. Django&#8217;s
tracking of parameters looks for <tt class="docutils literal"><span class="pre">%s</span></tt> and an escaped <tt class="docutils literal"><span class="pre">%</span></tt> character
like this isn&#8217;t detected. That will lead to incorrect results.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">where</span></tt> / <tt class="docutils literal"><span class="pre">tables</span></tt></p>
<p>You can define explicit SQL <tt class="docutils literal"><span class="pre">WHERE</span></tt> clauses — perhaps to perform
non-explicit joins — by using <tt class="docutils literal"><span class="pre">where</span></tt>. You can manually add tables to
the SQL <tt class="docutils literal"><span class="pre">FROM</span></tt> clause by using <tt class="docutils literal"><span class="pre">tables</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">where</span></tt> and <tt class="docutils literal"><span class="pre">tables</span></tt> both take a list of strings. All <tt class="docutils literal"><span class="pre">where</span></tt>
parameters are &#8220;AND&#8221;ed to any other search criteria.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s">&quot;foo=&#39;a&#39; OR bar = &#39;a&#39;&quot;</span><span class="p">,</span> <span class="s">&quot;baz = &#39;a&#39;&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>...translates (roughly) into the following SQL:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT * FROM blog_entry WHERE (foo=&#39;a&#39; OR bar=&#39;a&#39;) AND (baz=&#39;a&#39;)
</pre></div>
</div>
<p>Be careful when using the <tt class="docutils literal"><span class="pre">tables</span></tt> parameter if you&#8217;re specifying
tables that are already used in the query. When you add extra tables
via the <tt class="docutils literal"><span class="pre">tables</span></tt> parameter, Django assumes you want that table
included an extra time, if it is already included. That creates a
problem, since the table name will then be given an alias. If a table
appears multiple times in an SQL statement, the second and subsequent
occurrences must use aliases so the database can tell them apart. If
you&#8217;re referring to the extra table you added in the extra <tt class="docutils literal"><span class="pre">where</span></tt>
parameter this is going to cause errors.</p>
<p>Normally you&#8217;ll only be adding extra tables that don&#8217;t already appear
in the query. However, if the case outlined above does occur, there are
a few solutions. First, see if you can get by without including the
extra table and use the one already in the query. If that isn&#8217;t
possible, put your <tt class="docutils literal"><span class="pre">extra()</span></tt> call at the front of the queryset
construction so that your table is the first use of that table.
Finally, if all else fails, look at the query produced and rewrite your
<tt class="docutils literal"><span class="pre">where</span></tt> addition to use the alias given to your extra table. The
alias will be the same each time you construct the queryset in the same
way, so you can rely upon the alias name to not change.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">order_by</span></tt></p>
<p>If you need to order the resulting queryset using some of the new
fields or tables you have included via <tt class="docutils literal"><span class="pre">extra()</span></tt> use the <tt class="docutils literal"><span class="pre">order_by</span></tt>
parameter to <tt class="docutils literal"><span class="pre">extra()</span></tt> and pass in a sequence of strings. These
strings should either be model fields (as in the normal
<a class="reference internal" href="#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><tt class="xref py py-meth docutils literal"><span class="pre">order_by()</span></tt></a> method on querysets), of the form
<tt class="docutils literal"><span class="pre">table_name.column_name</span></tt> or an alias for a column that you specified
in the <tt class="docutils literal"><span class="pre">select</span></tt> parameter to <tt class="docutils literal"><span class="pre">extra()</span></tt>.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">q</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">select</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;is_recent&#39;</span><span class="p">:</span> <span class="s">&quot;pub_date &gt; &#39;2006-01-01&#39;&quot;</span><span class="p">})</span>
<span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">order_by</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;-is_recent&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>This would sort all the items for which <tt class="docutils literal"><span class="pre">is_recent</span></tt> is true to the
front of the result set (<tt class="docutils literal"><span class="pre">True</span></tt> sorts before <tt class="docutils literal"><span class="pre">False</span></tt> in a
descending ordering).</p>
<p>This shows, by the way, that you can make multiple calls to <tt class="docutils literal"><span class="pre">extra()</span></tt>
and it will behave as you expect (adding new constraints each time).</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">params</span></tt></p>
<p>The <tt class="docutils literal"><span class="pre">where</span></tt> parameter described above may use standard Python
database string placeholders — <tt class="docutils literal"><span class="pre">'%s'</span></tt> to indicate parameters the
database engine should automatically quote. The <tt class="docutils literal"><span class="pre">params</span></tt> argument is
a list of any extra parameters to be substituted.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;headline=</span><span class="si">%s</span><span class="s">&#39;</span><span class="p">],</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;Lennon&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>Always use <tt class="docutils literal"><span class="pre">params</span></tt> instead of embedding values directly into
<tt class="docutils literal"><span class="pre">where</span></tt> because <tt class="docutils literal"><span class="pre">params</span></tt> will ensure values are quoted correctly
according to your particular backend. For example, quotes will be
escaped correctly.</p>
<p>Bad:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s">&quot;headline=&#39;Lennon&#39;&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>Good:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">extra</span><span class="p">(</span><span class="n">where</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;headline=</span><span class="si">%s</span><span class="s">&#39;</span><span class="p">],</span> <span class="n">params</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;Lennon&#39;</span><span class="p">])</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If you are performing queries on MySQL, note that MySQL&#8217;s silent type coercion
may cause unexpected results when mixing types. If you query on a string
type column, but with an integer value, MySQL will coerce the types of all values
in the table to an integer before performing the comparison. For example, if your
table contains the values <tt class="docutils literal"><span class="pre">'abc'</span></tt>, <tt class="docutils literal"><span class="pre">'def'</span></tt> and you query for <tt class="docutils literal"><span class="pre">WHERE</span> <span class="pre">mycolumn=0</span></tt>,
both rows will match. To prevent this, perform the correct typecasting
before using the value in a query.</p>
</div>
</div>
<div class="section" id="s-defer">
<span id="defer"></span><h4>defer<a class="headerlink" href="#defer" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.defer">
<tt class="descname">defer</tt>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.defer" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>In some complex data-modeling situations, your models might contain a lot of
fields, some of which could contain a lot of data (for example, text fields),
or require expensive processing to convert them to Python objects. If you are
using the results of a queryset in some situation where you don&#8217;t know
if you need those particular fields when you initially fetch the data, you can
tell Django not to retrieve them from the database.</p>
<p>This is done by passing the names of the fields to not load to <tt class="docutils literal"><span class="pre">defer()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;headline&quot;</span><span class="p">,</span> <span class="s">&quot;body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>A queryset that has deferred fields will still return model instances. Each
deferred field will be retrieved from the database if you access that field
(one at a time, not all the deferred fields at once).</p>
<p>You can make multiple calls to <tt class="docutils literal"><span class="pre">defer()</span></tt>. Each call adds new fields to the
deferred set:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Defers both the body and headline fields.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">rating</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;headline&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The order in which fields are added to the deferred set does not matter.
Calling <tt class="docutils literal"><span class="pre">defer()</span></tt> with a field name that has already been deferred is
harmless (the field will still be deferred).</p>
<p>You can defer loading of fields in related models (if the related models are
loading via <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><tt class="xref py py-meth docutils literal"><span class="pre">select_related()</span></tt></a>) by using the standard double-underscore
notation to separate related fields:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">()</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;entry__headline&quot;</span><span class="p">,</span> <span class="s">&quot;entry__body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to clear the set of deferred fields, pass <tt class="docutils literal"><span class="pre">None</span></tt> as a parameter
to <tt class="docutils literal"><span class="pre">defer()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Load all fields immediately.</span>
<span class="n">my_queryset</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>Some fields in a model won&#8217;t be deferred, even if you ask for them. You can
never defer the loading of the primary key. If you are using
<a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><tt class="xref py py-meth docutils literal"><span class="pre">select_related()</span></tt></a> to retrieve related models, you shouldn&#8217;t defer the
loading of the field that connects from the primary model to the related
one, doing so will result in an error.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The <tt class="docutils literal"><span class="pre">defer()</span></tt> method (and its cousin, <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><tt class="xref py py-meth docutils literal"><span class="pre">only()</span></tt></a>, below) are only for
advanced use-cases. They provide an optimization for when you have analyzed
your queries closely and understand <em>exactly</em> what information you need and
have measured that the difference between returning the fields you need and
the full set of fields for the model will be significant.</p>
<p class="last">Even if you think you are in the advanced use-case situation, <strong>only use
defer() when you cannot, at queryset load time, determine if you will need
the extra fields or not</strong>. If you are frequently loading and using a
particular subset of your data, the best choice you can make is to
normalize your models and put the non-loaded data into a separate model
(and database table). If the columns <em>must</em> stay in the one table for some
reason, create a model with <tt class="docutils literal"><span class="pre">Meta.managed</span> <span class="pre">=</span> <span class="pre">False</span></tt> (see the
<a class="reference internal" href="options.html#django.db.models.Options.managed" title="django.db.models.Options.managed"><tt class="xref py py-attr docutils literal"><span class="pre">managed</span> <span class="pre">attribute</span></tt></a> documentation)
containing just the fields you normally need to load and use that where you
might otherwise call <tt class="docutils literal"><span class="pre">defer()</span></tt>. This makes your code more explicit to the
reader, is slightly faster and consumes a little less memory in the Python
process.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for instances with
deferred fields, only the loaded fields will be saved. See
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for more details.</p>
</div>
</div>
<div class="section" id="s-only">
<span id="only"></span><h4>only<a class="headerlink" href="#only" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.only">
<tt class="descname">only</tt>(<em>*fields</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.only" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The <tt class="docutils literal"><span class="pre">only()</span></tt> method is more or less the opposite of <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">defer()</span></tt></a>. You call
it with the fields that should <em>not</em> be deferred when retrieving a model.  If
you have a model where almost all the fields need to be deferred, using
<tt class="docutils literal"><span class="pre">only()</span></tt> to specify the complementary set of fields can result in simpler
code.</p>
<p>Suppose you have a model with fields <tt class="docutils literal"><span class="pre">name</span></tt>, <tt class="docutils literal"><span class="pre">age</span></tt> and <tt class="docutils literal"><span class="pre">biography</span></tt>. The
following two querysets are the same, in terms of deferred fields:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;age&quot;</span><span class="p">,</span> <span class="s">&quot;biography&quot;</span><span class="p">)</span>
<span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&quot;name&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Whenever you call <tt class="docutils literal"><span class="pre">only()</span></tt> it <em>replaces</em> the set of fields to load
immediately. The method&#8217;s name is mnemonic: <strong>only</strong> those fields are loaded
immediately; the remainder are deferred. Thus, successive calls to <tt class="docutils literal"><span class="pre">only()</span></tt>
result in only the final fields being considered:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># This will defer all fields except the headline.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&quot;body&quot;</span><span class="p">,</span> <span class="s">&quot;rating&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&quot;headline&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since <tt class="docutils literal"><span class="pre">defer()</span></tt> acts incrementally (adding fields to the deferred list), you
can combine calls to <tt class="docutils literal"><span class="pre">only()</span></tt> and <tt class="docutils literal"><span class="pre">defer()</span></tt> and things will behave
logically:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Final result is that everything except &quot;headline&quot; is deferred.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&quot;headline&quot;</span><span class="p">,</span> <span class="s">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;body&quot;</span><span class="p">)</span>

<span class="c"># Final result loads headline and body immediately (only() replaces any</span>
<span class="c"># existing set of fields).</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">defer</span><span class="p">(</span><span class="s">&quot;body&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">only</span><span class="p">(</span><span class="s">&quot;headline&quot;</span><span class="p">,</span> <span class="s">&quot;body&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>All of the cautions in the note for the <a class="reference internal" href="#django.db.models.query.QuerySet.defer" title="django.db.models.query.QuerySet.defer"><tt class="xref py py-meth docutils literal"><span class="pre">defer()</span></tt></a> documentation apply to
<tt class="docutils literal"><span class="pre">only()</span></tt> as well. Use it cautiously and only after exhausting your other
options.</p>
<p>Using <a class="reference internal" href="#django.db.models.query.QuerySet.only" title="django.db.models.query.QuerySet.only"><tt class="xref py py-meth docutils literal"><span class="pre">only()</span></tt></a> and omitting a field requested using <a class="reference internal" href="#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><tt class="xref py py-meth docutils literal"><span class="pre">select_related()</span></tt></a>
is an error as well.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for instances with
deferred fields, only the loaded fields will be saved. See
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> for more details.</p>
</div>
</div>
<div class="section" id="s-using">
<span id="using"></span><h4>using<a class="headerlink" href="#using" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.using">
<tt class="descname">using</tt>(<em>alias</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.using" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This method is for controlling which database the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> will be
evaluated against if you are using more than one database.  The only argument
this method takes is the alias of a database, as defined in
<a class="reference internal" href="../settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre># queries the database with the &#39;default&#39; alias.
&gt;&gt;&gt; Entry.objects.all()

# queries the database with the &#39;backup&#39; alias
&gt;&gt;&gt; Entry.objects.using(&#39;backup&#39;)
</pre></div>
</div>
</div>
<div class="section" id="s-select-for-update">
<span id="select-for-update"></span><h4>select_for_update<a class="headerlink" href="#select-for-update" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.select_for_update">
<tt class="descname">select_for_update</tt>(<em>nowait=False</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.select_for_update" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a queryset that will lock rows until the end of the transaction,
generating a <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></tt> SQL statement on supported databases.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_for_update</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">author</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="p">)</span>
</pre></div>
</div>
<p>All matched entries will be locked until the end of the transaction block,
meaning that other transactions will be prevented from changing or acquiring
locks on them.</p>
<p>Usually, if another transaction has already acquired a lock on one of the
selected rows, the query will block until the lock is released. If this is
not the behavior you want, call <tt class="docutils literal"><span class="pre">select_for_update(nowait=True)</span></tt>. This will
make the call non-blocking. If a conflicting lock is already acquired by
another transaction, <a class="reference internal" href="../exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><tt class="xref py py-exc docutils literal"><span class="pre">DatabaseError</span></tt></a> will be raised when the
queryset is evaluated.</p>
<p>Currently, the <tt class="docutils literal"><span class="pre">postgresql_psycopg2</span></tt>, <tt class="docutils literal"><span class="pre">oracle</span></tt>, and <tt class="docutils literal"><span class="pre">mysql</span></tt> database
backends support <tt class="docutils literal"><span class="pre">select_for_update()</span></tt>. However, MySQL has no support for the
<tt class="docutils literal"><span class="pre">nowait</span></tt> argument. Obviously, users of external third-party backends should
check with their backend&#8217;s documentation for specifics in those cases.</p>
<p>Passing <tt class="docutils literal"><span class="pre">nowait=True</span></tt> to <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> using database backends that
do not support <tt class="docutils literal"><span class="pre">nowait</span></tt>, such as MySQL, will cause a
<a class="reference internal" href="../exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><tt class="xref py py-exc docutils literal"><span class="pre">DatabaseError</span></tt></a> to be raised. This is in order to prevent code
unexpectedly blocking.</p>
<p>Evaluating a queryset with <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> in autocommit mode is
a <a class="reference internal" href="../exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><tt class="xref py py-exc docutils literal"><span class="pre">TransactionManagementError</span></tt></a> error because the
rows are not locked in that case. If allowed, this would facilitate data
corruption and could easily be caused by calling code that expects to be run in
a transaction outside of one.</p>
<p>Using <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> on backends which do not support
<tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></tt> (such as SQLite) will have no effect.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6.3:</span> <p>It is now an error to execute a query with <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> in
autocommit mode. With earlier releases in the 1.6 series it was a no-op.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Although <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> normally fails in autocommit mode, since
<a class="reference internal" href="../../topics/testing/tools.html#django.test.TestCase" title="django.test.TestCase"><tt class="xref py py-class docutils literal"><span class="pre">TestCase</span></tt></a> automatically wraps each test in a
transaction, calling <tt class="docutils literal"><span class="pre">select_for_update()</span></tt> in a <tt class="docutils literal"><span class="pre">TestCase</span></tt> even outside
an <a class="reference internal" href="../../topics/db/transactions.html#django.db.transaction.atomic" title="django.db.transaction.atomic"><tt class="xref py py-func docutils literal"><span class="pre">atomic()</span></tt></a> block will (perhaps unexpectedly)
pass without raising a <tt class="docutils literal"><span class="pre">TransactionManagementError</span></tt>. To properly test
<tt class="docutils literal"><span class="pre">select_for_update()</span></tt> you should use
<a class="reference internal" href="../../topics/testing/tools.html#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><tt class="xref py py-class docutils literal"><span class="pre">TransactionTestCase</span></tt></a>.</p>
</div>
</div>
<div class="section" id="s-raw">
<span id="raw"></span><h4>raw<a class="headerlink" href="#raw" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.raw">
<tt class="descname">raw</tt>(<em>raw_query</em>, <em>params=None</em>, <em>translations=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.raw" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p><tt class="docutils literal"><span class="pre">raw</span></tt> was moved to the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> class. It was previously only on
<a class="reference internal" href="../../topics/db/managers.html#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">Manager</span></tt></a>.</p>
</div>
<p>Takes a raw SQL query, executes it, and returns a
<tt class="docutils literal"><span class="pre">django.db.models.query.RawQuerySet</span></tt> instance. This <tt class="docutils literal"><span class="pre">RawQuerySet</span></tt> instance
can be iterated over just like an normal <tt class="docutils literal"><span class="pre">QuerySet</span></tt> to provide object instances.</p>
<p>See the <a class="reference internal" href="../../topics/db/sql.html"><em>Performing raw SQL queries</em></a> for more information.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><tt class="docutils literal"><span class="pre">raw()</span></tt> always triggers a new query and doesn&#8217;t account for previous
filtering. As such, it should generally be called from the <tt class="docutils literal"><span class="pre">Manager</span></tt> or
from a fresh <tt class="docutils literal"><span class="pre">QuerySet</span></tt> instance.</p>
</div>
</div>
</div>
<div class="section" id="s-methods-that-do-not-return-querysets">
<span id="methods-that-do-not-return-querysets"></span><h3>Methods that do not return QuerySets<a class="headerlink" href="#methods-that-do-not-return-querysets" title="Permalink to this headline">¶</a></h3>
<p>The following <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods evaluate the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and return
something <em>other than</em> a <tt class="docutils literal"><span class="pre">QuerySet</span></tt>.</p>
<p>These methods do not use a cache (see <a class="reference internal" href="../../topics/db/queries.html#caching-and-querysets"><em>Caching and QuerySets</em></a>). Rather,
they query the database each time they&#8217;re called.</p>
<div class="section" id="s-get">
<span id="get"></span><h4>get<a class="headerlink" href="#get" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.get">
<tt class="descname">get</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.get" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns the object matching the given lookup parameters, which should be in
the format described in <a class="reference internal" href="#id4">Field lookups</a>.</p>
<p><tt class="docutils literal"><span class="pre">get()</span></tt> raises <a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><tt class="xref py py-exc docutils literal"><span class="pre">MultipleObjectsReturned</span></tt></a> if more
than one object was found. The
<a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><tt class="xref py py-exc docutils literal"><span class="pre">MultipleObjectsReturned</span></tt></a> exception is an
attribute of the model class.</p>
<p><tt class="docutils literal"><span class="pre">get()</span></tt> raises a <a class="reference internal" href="../exceptions.html#django.core.exceptions.DoesNotExist" title="django.core.exceptions.DoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">DoesNotExist</span></tt></a> exception if an
object wasn&#8217;t found for the given parameters. This exception is also an
attribute of the model class. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s">&#39;foo&#39;</span><span class="p">)</span> <span class="c"># raises Entry.DoesNotExist</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../exceptions.html#django.core.exceptions.DoesNotExist" title="django.core.exceptions.DoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">DoesNotExist</span></tt></a> exception inherits from
<a class="reference internal" href="../exceptions.html#django.core.exceptions.ObjectDoesNotExist" title="django.core.exceptions.ObjectDoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">django.core.exceptions.ObjectDoesNotExist</span></tt></a>, so you can target multiple
<a class="reference internal" href="../exceptions.html#django.core.exceptions.DoesNotExist" title="django.core.exceptions.DoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">DoesNotExist</span></tt></a> exceptions. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.core.exceptions</span> <span class="kn">import</span> <span class="n">ObjectDoesNotExist</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">except</span> <span class="n">ObjectDoesNotExist</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s">&quot;Either the entry or blog doesn&#39;t exist.&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-create">
<span id="create"></span><h4>create<a class="headerlink" href="#create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.create">
<tt class="descname">create</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A convenience method for creating an object and saving it all in one step.  Thus:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&quot;Bruce&quot;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&quot;Springsteen&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">p</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&quot;Bruce&quot;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&quot;Springsteen&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">force_insert</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>are equivalent.</p>
<p>The <a class="reference internal" href="instances.html#ref-models-force-insert"><em>force_insert</em></a> parameter is documented
elsewhere, but all it means is that a new object will always be created.
Normally you won&#8217;t need to worry about this. However, if your model contains a
manual primary key value that you set and if that value already exists in the
database, a call to <tt class="docutils literal"><span class="pre">create()</span></tt> will fail with an
<a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><tt class="xref py py-exc docutils literal"><span class="pre">IntegrityError</span></tt></a> since primary keys must be unique. Be
prepared to handle the exception if you are using manual primary keys.</p>
</div>
<div class="section" id="s-get-or-create">
<span id="get-or-create"></span><h4>get_or_create<a class="headerlink" href="#get-or-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.get_or_create">
<tt class="descname">get_or_create</tt>(<em>defaults=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.get_or_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>A convenience method for looking up an object with the given <tt class="docutils literal"><span class="pre">kwargs</span></tt> (may be
empty if your model has defaults for all fields), creating one if necessary.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.6:</span> <p>Older versions of Django required <tt class="docutils literal"><span class="pre">kwargs</span></tt>.</p>
</div>
<p>Returns a tuple of <tt class="docutils literal"><span class="pre">(object,</span> <span class="pre">created)</span></tt>, where <tt class="docutils literal"><span class="pre">object</span></tt> is the retrieved or
created object and <tt class="docutils literal"><span class="pre">created</span></tt> is a boolean specifying whether a new object was
created.</p>
<p>This is meant as a shortcut to boilerplatish code. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span>
<span class="k">except</span> <span class="n">Person</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">,</span> <span class="n">birthday</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">1940</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">9</span><span class="p">))</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This pattern gets quite unwieldy as the number of fields in a model goes up.
The above example can be rewritten using <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">obj</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">,</span>
                  <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;birthday&#39;</span><span class="p">:</span> <span class="n">date</span><span class="p">(</span><span class="mi">1940</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">9</span><span class="p">)})</span>
</pre></div>
</div>
<p>Any keyword arguments passed to <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> — <em>except</em> an optional one
called <tt class="docutils literal"><span class="pre">defaults</span></tt> — will be used in a <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a> call. If an object is
found, <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> returns a tuple of that object and <tt class="docutils literal"><span class="pre">False</span></tt>. If
multiple objects are found, <tt class="docutils literal"><span class="pre">get_or_create</span></tt> raises
<a class="reference internal" href="../exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><tt class="xref py py-exc docutils literal"><span class="pre">MultipleObjectsReturned</span></tt></a>. If an object is <em>not</em>
found, <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> will instantiate and save a new object, returning a
tuple of the new object and <tt class="docutils literal"><span class="pre">True</span></tt>. The new object will be created roughly
according to this algorithm:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">params</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">([(</span><span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="k">if</span> <span class="s">&#39;__&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">k</span><span class="p">])</span>
<span class="n">params</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">defaults</span><span class="p">)</span>
<span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>
<span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>In English, that means start with any non-<tt class="docutils literal"><span class="pre">'defaults'</span></tt> keyword argument that
doesn&#8217;t contain a double underscore (which would indicate a non-exact lookup).
Then add the contents of <tt class="docutils literal"><span class="pre">defaults</span></tt>, overriding any keys if necessary, and
use the result as the keyword arguments to the model class. As hinted at
above, this is a simplification of the algorithm that is used, but it contains
all the pertinent details. The internal implementation has some more
error-checking than this and handles some extra edge-conditions; if you&#8217;re
interested, read the code.</p>
<p>If you have a field named <tt class="docutils literal"><span class="pre">defaults</span></tt> and want to use it as an exact lookup in
<tt class="docutils literal"><span class="pre">get_or_create()</span></tt>, just use <tt class="docutils literal"><span class="pre">'defaults__exact'</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Foo</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">defaults__exact</span><span class="o">=</span><span class="s">&#39;bar&#39;</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="p">{</span><span class="s">&#39;defaults&#39;</span><span class="p">:</span> <span class="s">&#39;baz&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> method has similar error behavior to <a class="reference internal" href="#django.db.models.query.QuerySet.create" title="django.db.models.query.QuerySet.create"><tt class="xref py py-meth docutils literal"><span class="pre">create()</span></tt></a>
when you&#8217;re using manually specified primary keys. If an object needs to be
created and the key already exists in the database, an
<a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><tt class="xref py py-exc docutils literal"><span class="pre">IntegrityError</span></tt></a> will be raised.</p>
<p>This method is atomic assuming correct usage, correct database configuration,
and correct behavior of the underlying database. However, if uniqueness is not
enforced at the database level for the <tt class="docutils literal"><span class="pre">kwargs</span></tt> used in a <tt class="docutils literal"><span class="pre">get_or_create</span></tt>
call (see <a class="reference internal" href="fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><tt class="xref py py-attr docutils literal"><span class="pre">unique</span></tt></a> or
<a class="reference internal" href="options.html#django.db.models.Options.unique_together" title="django.db.models.Options.unique_together"><tt class="xref py py-attr docutils literal"><span class="pre">unique_together</span></tt></a>), this method is prone to a
race-condition which can result in multiple rows with the same parameters being
inserted simultaneously.</p>
<p>If you are using MySQL, be sure to use the <tt class="docutils literal"><span class="pre">READ</span> <span class="pre">COMMITTED</span></tt> isolation level
rather than <tt class="docutils literal"><span class="pre">REPEATABLE</span> <span class="pre">READ</span></tt> (the default), otherwise you may see cases
where <tt class="docutils literal"><span class="pre">get_or_create</span></tt> will raise an <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><tt class="xref py py-exc docutils literal"><span class="pre">IntegrityError</span></tt></a> but the
object won&#8217;t appear in a subsequent <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a>
call.</p>
<p>Finally, a word on using <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> in Django views. Please make sure
to use it only in <tt class="docutils literal"><span class="pre">POST</span></tt> requests unless you have a good reason not to.
<tt class="docutils literal"><span class="pre">GET</span></tt> requests shouldn&#8217;t have any effect on data. Instead, use <tt class="docutils literal"><span class="pre">POST</span></tt>
whenever a request to a page has a side effect on your data. For more, see
<a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1">Safe methods</a> in the HTTP spec.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>You can use <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> through <a class="reference internal" href="fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><tt class="xref py py-class docutils literal"><span class="pre">ManyToManyField</span></tt></a>
attributes and reverse relations. In that case you will restrict the queries
inside the context of that relation. That could lead you to some integrity
problems if you don&#8217;t use it consistently.</p>
<p>Being the following models:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Chapter</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">title</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">256</span><span class="p">)</span>
    <span class="n">chapters</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Chapter</span><span class="p">)</span>
</pre></div>
</div>
<p>You can use <tt class="docutils literal"><span class="pre">get_or_create()</span></tt> through Book&#8217;s chapters field, but it only
fetches inside the context of that book:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">book</span> <span class="o">=</span> <span class="n">Book</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&quot;Ulysses&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&quot;Telemachus&quot;</span><span class="p">)</span>
<span class="go">(&lt;Chapter: Telemachus&gt;, True)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&quot;Telemachus&quot;</span><span class="p">)</span>
<span class="go">(&lt;Chapter: Telemachus&gt;, False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Chapter</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&quot;Chapter 1&quot;</span><span class="p">)</span>
<span class="go">&lt;Chapter: Chapter 1&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">book</span><span class="o">.</span><span class="n">chapters</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s">&quot;Chapter 1&quot;</span><span class="p">)</span>
<span class="go"># Raises IntegrityError</span>
</pre></div>
</div>
<p class="last">This is happening because it&#8217;s trying to get or create &#8220;Chapter 1&#8221; through the
book &#8220;Ulysses&#8221;, but it can&#8217;t do any of them: the relation can&#8217;t fetch that
chapter because it isn&#8217;t related to that book, but it can&#8217;t create it either
because <tt class="docutils literal"><span class="pre">title</span></tt> field should be unique.</p>
</div>
</div>
<div class="section" id="s-update-or-create">
<span id="update-or-create"></span><h4>update_or_create<a class="headerlink" href="#update-or-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.update_or_create">
<tt class="descname">update_or_create</tt>(<em>defaults=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.update_or_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>A convenience method for updating an object with the given <tt class="docutils literal"><span class="pre">kwargs</span></tt>, creating
a new one if necessary. The <tt class="docutils literal"><span class="pre">defaults</span></tt> is a dictionary of (field, value)
pairs used to update the object.</p>
<p>Returns a tuple of <tt class="docutils literal"><span class="pre">(object,</span> <span class="pre">created)</span></tt>, where <tt class="docutils literal"><span class="pre">object</span></tt> is the created or
updated object and <tt class="docutils literal"><span class="pre">created</span></tt> is a boolean specifying whether a new object was
created.</p>
<p>The <tt class="docutils literal"><span class="pre">update_or_create</span></tt> method tries to fetch an object from database based on
the given <tt class="docutils literal"><span class="pre">kwargs</span></tt>. If a match is found, it updates the fields passed in the
<tt class="docutils literal"><span class="pre">defaults</span></tt> dictionary.</p>
<p>This is meant as a shortcut to boilerplatish code. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">updated_values</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
        <span class="nb">setattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="k">except</span> <span class="n">Person</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
    <span class="n">updated_values</span><span class="o">.</span><span class="n">update</span><span class="p">({</span><span class="s">&#39;first_name&#39;</span><span class="p">:</span> <span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="s">&#39;last_name&#39;</span><span class="p">:</span> <span class="s">&#39;Lennon&#39;</span><span class="p">})</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">Person</span><span class="p">(</span><span class="o">**</span><span class="n">updated_values</span><span class="p">)</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This pattern gets quite unwieldy as the number of fields in a model goes up.
The above example can be rewritten using <tt class="docutils literal"><span class="pre">update_or_create()</span></tt> like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">obj</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="n">Person</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update_or_create</span><span class="p">(</span>
    <span class="n">first_name</span><span class="o">=</span><span class="s">&#39;John&#39;</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">,</span> <span class="n">defaults</span><span class="o">=</span><span class="n">updated_values</span><span class="p">)</span>
</pre></div>
</div>
<p>For detailed description how names passed in <tt class="docutils literal"><span class="pre">kwargs</span></tt> are resolved see
<a class="reference internal" href="#django.db.models.query.QuerySet.get_or_create" title="django.db.models.query.QuerySet.get_or_create"><tt class="xref py py-meth docutils literal"><span class="pre">get_or_create()</span></tt></a>.</p>
<p>As described above in <a class="reference internal" href="#django.db.models.query.QuerySet.get_or_create" title="django.db.models.query.QuerySet.get_or_create"><tt class="xref py py-meth docutils literal"><span class="pre">get_or_create()</span></tt></a>, this method is prone to a
race-condition which can result in multiple rows being inserted simultaneously
if uniqueness is not enforced at the database level.</p>
</div>
<div class="section" id="s-bulk-create">
<span id="bulk-create"></span><h4>bulk_create<a class="headerlink" href="#bulk-create" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.bulk_create">
<tt class="descname">bulk_create</tt>(<em>objs</em>, <em>batch_size=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.bulk_create" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This method inserts the provided list of objects into the database in an
efficient manner (generally only 1 query, no matter how many objects there
are):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">bulk_create</span><span class="p">([</span>
<span class="gp">... </span>    <span class="n">Entry</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&quot;Django 1.0 Released&quot;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Entry</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&quot;Django 1.1 Announced&quot;</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Entry</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s">&quot;Breaking: Django is awesome&quot;</span><span class="p">)</span>
<span class="gp">... </span><span class="p">])</span>
</pre></div>
</div>
<p>This has a number of caveats though:</p>
<ul class="simple">
<li>The model&#8217;s <tt class="docutils literal"><span class="pre">save()</span></tt> method will not be called, and the <tt class="docutils literal"><span class="pre">pre_save</span></tt> and
<tt class="docutils literal"><span class="pre">post_save</span></tt> signals will not be sent.</li>
<li>It does not work with child models in a multi-table inheritance scenario.</li>
<li>If the model&#8217;s primary key is an <a class="reference internal" href="fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><tt class="xref py py-class docutils literal"><span class="pre">AutoField</span></tt></a> it
does not retrieve and set the primary key attribute, as <tt class="docutils literal"><span class="pre">save()</span></tt> does.</li>
<li>It does not work with many-to-many relationships.</li>
</ul>
<p>The <tt class="docutils literal"><span class="pre">batch_size</span></tt> parameter controls how many objects are created in single
query. The default is to create all objects in one batch, except for SQLite
where the default is such that at most 999 variables per query are used.</p>
</div>
<div class="section" id="s-count">
<span id="count"></span><h4>count<a class="headerlink" href="#count" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.count">
<tt class="descname">count</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.count" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns an integer representing the number of objects in the database matching
the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. The <tt class="docutils literal"><span class="pre">count()</span></tt> method never raises exceptions.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Returns the total number of entries in the database.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>

<span class="c"># Returns the number of entries whose headline contains &#39;Lennon&#39;</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>A <tt class="docutils literal"><span class="pre">count()</span></tt> call performs a <tt class="docutils literal"><span class="pre">SELECT</span> <span class="pre">COUNT(*)</span></tt> behind the scenes, so you
should always use <tt class="docutils literal"><span class="pre">count()</span></tt> rather than loading all of the record into Python
objects and calling <tt class="docutils literal"><span class="pre">len()</span></tt> on the result (unless you need to load the
objects into memory anyway, in which case <tt class="docutils literal"><span class="pre">len()</span></tt> will be faster).</p>
<p>Depending on which database you&#8217;re using (e.g. PostgreSQL vs. MySQL),
<tt class="docutils literal"><span class="pre">count()</span></tt> may return a long integer instead of a normal Python integer. This
is an underlying implementation quirk that shouldn&#8217;t pose any real-world
problems.</p>
<p>Note that if you want the number of items in a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> and are also
retrieving model instances from it (for example, by iterating over it), it&#8217;s
probably more efficient to use <tt class="docutils literal"><span class="pre">len(queryset)</span></tt> which won&#8217;t cause an extra
database query like <tt class="docutils literal"><span class="pre">count()</span></tt> would.</p>
</div>
<div class="section" id="s-in-bulk">
<span id="in-bulk"></span><h4>in_bulk<a class="headerlink" href="#in-bulk" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.in_bulk">
<tt class="descname">in_bulk</tt>(<em>id_list</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.in_bulk" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Takes a list of primary-key values and returns a dictionary mapping each
primary-key value to an instance of the object with the given ID.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([</span><span class="mi">1</span><span class="p">])</span>
<span class="go">{1: &lt;Blog: Beatles Blog&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">])</span>
<span class="go">{1: &lt;Blog: Beatles Blog&gt;, 2: &lt;Blog: Cheddar Talk&gt;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">in_bulk</span><span class="p">([])</span>
<span class="go">{}</span>
</pre></div>
</div>
<p>If you pass <tt class="docutils literal"><span class="pre">in_bulk()</span></tt> an empty list, you&#8217;ll get an empty dictionary.</p>
</div>
<div class="section" id="s-iterator">
<span id="iterator"></span><h4>iterator<a class="headerlink" href="#iterator" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.iterator">
<tt class="descname">iterator</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.iterator" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Evaluates the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> (by performing the query) and returns an iterator
(see <span class="target" id="index-0"></span><a class="pep reference external" href="http://www.python.org/dev/peps/pep-0234"><strong>PEP 234</strong></a>) over the results. A <tt class="docutils literal"><span class="pre">QuerySet</span></tt> typically caches its results
internally so that repeated evaluations do not result in additional queries. In
contrast, <tt class="docutils literal"><span class="pre">iterator()</span></tt> will read results directly, without doing any caching
at the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> level (internally, the default iterator calls <tt class="docutils literal"><span class="pre">iterator()</span></tt>
and caches the return value). For a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> which returns a large number of
objects that you only need to access once, this can result in better
performance and a significant reduction in memory.</p>
<p>Note that using <tt class="docutils literal"><span class="pre">iterator()</span></tt> on a <tt class="docutils literal"><span class="pre">QuerySet</span></tt> which has already been
evaluated will force it to evaluate again, repeating the query.</p>
<p>Also, use of <tt class="docutils literal"><span class="pre">iterator()</span></tt> causes previous <tt class="docutils literal"><span class="pre">prefetch_related()</span></tt> calls to be
ignored since these two optimizations do not make sense together.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Some Python database drivers like <tt class="docutils literal"><span class="pre">psycopg2</span></tt> perform caching if using
client side cursors (instantiated with <tt class="docutils literal"><span class="pre">connection.cursor()</span></tt> and what
Django&#8217;s ORM uses). Using <tt class="docutils literal"><span class="pre">iterator()</span></tt> does not affect caching at the
database driver level. To disable this caching, look at <a class="reference external" href="http://initd.org/psycopg/docs/usage.html#server-side-cursors">server side
cursors</a>.</p>
</div>
</div>
<div class="section" id="s-latest">
<span id="latest"></span><h4>latest<a class="headerlink" href="#latest" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.latest">
<tt class="descname">latest</tt>(<em>field_name=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.latest" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns the latest object in the table, by date, using the <tt class="docutils literal"><span class="pre">field_name</span></tt>
provided as the date field.</p>
<p>This example returns the latest <tt class="docutils literal"><span class="pre">Entry</span></tt> in the table, according to the
<tt class="docutils literal"><span class="pre">pub_date</span></tt> field:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">latest</span><span class="p">(</span><span class="s">&#39;pub_date&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If your model&#8217;s <a class="reference internal" href="../../topics/db/models.html#meta-options"><em>Meta</em></a> specifies
<a class="reference internal" href="options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><tt class="xref py py-attr docutils literal"><span class="pre">get_latest_by</span></tt></a>, you can leave off the
<tt class="docutils literal"><span class="pre">field_name</span></tt> argument to <tt class="docutils literal"><span class="pre">earliest()</span></tt> or <tt class="docutils literal"><span class="pre">latest()</span></tt>. Django will use the
field specified in <a class="reference internal" href="options.html#django.db.models.Options.get_latest_by" title="django.db.models.Options.get_latest_by"><tt class="xref py py-attr docutils literal"><span class="pre">get_latest_by</span></tt></a> by default.</p>
<p>Like <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a>, <tt class="docutils literal"><span class="pre">earliest()</span></tt> and <tt class="docutils literal"><span class="pre">latest()</span></tt> raise
<a class="reference internal" href="../exceptions.html#django.core.exceptions.DoesNotExist" title="django.core.exceptions.DoesNotExist"><tt class="xref py py-exc docutils literal"><span class="pre">DoesNotExist</span></tt></a> if there is no object with the
given parameters.</p>
<p>Note that <tt class="docutils literal"><span class="pre">earliest()</span></tt> and <tt class="docutils literal"><span class="pre">latest()</span></tt> exist purely for convenience and
readability.</p>
</div>
<div class="section" id="s-earliest">
<span id="earliest"></span><h4>earliest<a class="headerlink" href="#earliest" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.earliest">
<tt class="descname">earliest</tt>(<em>field_name=None</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.earliest" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Works otherwise like <a class="reference internal" href="#django.db.models.query.QuerySet.latest" title="django.db.models.query.QuerySet.latest"><tt class="xref py py-meth docutils literal"><span class="pre">latest()</span></tt></a> except
the direction is changed.</p>
</div>
<div class="section" id="s-first">
<span id="first"></span><h4>first<a class="headerlink" href="#first" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.first">
<tt class="descname">first</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.first" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Returns the first object matched by the queryset, or <tt class="docutils literal"><span class="pre">None</span></tt> if there
is no matching object. If the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> has no ordering defined, then the
queryset is automatically ordered by the primary key.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">p</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;title&#39;</span><span class="p">,</span> <span class="s">&#39;pub_date&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that <tt class="docutils literal"><span class="pre">first()</span></tt> is a convenience method, the following code sample is
equivalent to the above example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">try</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;title&#39;</span><span class="p">,</span> <span class="s">&#39;pub_date&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="bp">None</span>
</pre></div>
</div>
</div>
<div class="section" id="s-last">
<span id="last"></span><h4>last<a class="headerlink" href="#last" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.last">
<tt class="descname">last</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.last" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>Works like  <a class="reference internal" href="#django.db.models.query.QuerySet.first" title="django.db.models.query.QuerySet.first"><tt class="xref py py-meth docutils literal"><span class="pre">first()</span></tt></a>, but returns the last object in the queryset.</p>
</div>
<div class="section" id="s-aggregate">
<span id="aggregate"></span><h4>aggregate<a class="headerlink" href="#aggregate" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.aggregate">
<tt class="descname">aggregate</tt>(<em>*args</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.aggregate" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns a dictionary of aggregate values (averages, sums, etc) calculated over
the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>. Each argument to <tt class="docutils literal"><span class="pre">aggregate()</span></tt> specifies a value that will
be included in the dictionary that is returned.</p>
<p>The aggregation functions that are provided by Django are described in
<a class="reference internal" href="#id5">Aggregation Functions</a> below.</p>
<p>Aggregates specified using keyword arguments will use the keyword as the name
for the annotation. Anonymous arguments will have a name generated for them
based upon the name of the aggregate function and the model field that is being
aggregated.</p>
<p>For example, when you are working with blog entries, you may want to know the
number of authors that have contributed blog entries:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">Count</span><span class="p">(</span><span class="s">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">{&#39;entry__count&#39;: 16}</span>
</pre></div>
</div>
<p>By using a keyword argument to specify the aggregate function, you can
control the name of the aggregation value that is returned:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">number_of_entries</span><span class="o">=</span><span class="n">Count</span><span class="p">(</span><span class="s">&#39;entry&#39;</span><span class="p">))</span>
<span class="go">{&#39;number_of_entries&#39;: 16}</span>
</pre></div>
</div>
<p>For an in-depth discussion of aggregation, see <a class="reference internal" href="../../topics/db/aggregation.html"><em>the topic guide on
Aggregation</em></a>.</p>
</div>
<div class="section" id="s-exists">
<span id="exists"></span><h4>exists<a class="headerlink" href="#exists" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.exists">
<tt class="descname">exists</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.exists" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Returns <tt class="docutils literal"><span class="pre">True</span></tt> if the <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> contains any results, and <tt class="docutils literal"><span class="pre">False</span></tt>
if not. This tries to perform the query in the simplest and fastest way
possible, but it <em>does</em> execute nearly the same query as a normal
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> query.</p>
<p><a class="reference internal" href="#django.db.models.query.QuerySet.exists" title="django.db.models.query.QuerySet.exists"><tt class="xref py py-meth docutils literal"><span class="pre">exists()</span></tt></a> is useful for searches relating to both
object membership in a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> and to the existence of any objects in
a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a>, particularly in the context of a large <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a>.</p>
<p>The most efficient method of finding whether a model with a unique field
(e.g. <tt class="docutils literal"><span class="pre">primary_key</span></tt>) is a member of a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">123</span><span class="p">)</span>
<span class="k">if</span> <span class="n">some_queryset</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">entry</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span><span class="o">.</span><span class="n">exists</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="s">&quot;Entry contained in queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Which will be faster than the following which requires evaluating and iterating
through the entire queryset:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">some_queryset</span><span class="p">:</span>
   <span class="k">print</span><span class="p">(</span><span class="s">&quot;Entry contained in QuerySet&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>And to find whether a queryset contains any items:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">some_queryset</span><span class="o">.</span><span class="n">exists</span><span class="p">():</span>
    <span class="k">print</span><span class="p">(</span><span class="s">&quot;There is at least one object in some_queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Which will be faster than:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">some_queryset</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="s">&quot;There is at least one object in some_queryset&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>... but not by a large degree (hence needing a large queryset for efficiency
gains).</p>
<p>Additionally, if a <tt class="docutils literal"><span class="pre">some_queryset</span></tt> has not yet been evaluated, but you know
that it will be at some point, then using <tt class="docutils literal"><span class="pre">some_queryset.exists()</span></tt> will do
more overall work (one query for the existence check plus an extra one to later
retrieve the results) than simply using <tt class="docutils literal"><span class="pre">bool(some_queryset)</span></tt>, which
retrieves the results and then checks if any were returned.</p>
</div>
<div class="section" id="s-update">
<span id="update"></span><h4>update<a class="headerlink" href="#update" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.update">
<tt class="descname">update</tt>(<em>**kwargs</em>)<a class="headerlink" href="#django.db.models.query.QuerySet.update" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Performs an SQL update query for the specified fields, and returns
the number of rows matched (which may not be equal to the number of rows
updated if some rows already have the new value).</p>
<p>For example, to turn comments off for all blog entries published in 2010,
you could do this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</pre></div>
</div>
<p>(This assumes your <tt class="docutils literal"><span class="pre">Entry</span></tt> model has fields <tt class="docutils literal"><span class="pre">pub_date</span></tt> and <tt class="docutils literal"><span class="pre">comments_on</span></tt>.)</p>
<p>You can update multiple fields — there&#8217;s no limit on how many. For example,
here we update the <tt class="docutils literal"><span class="pre">comments_on</span></tt> and <tt class="docutils literal"><span class="pre">headline</span></tt> fields:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">headline</span><span class="o">=</span><span class="s">&#39;This is old&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">update()</span></tt> method is applied instantly, and the only restriction on the
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> that is updated is that it can only update columns in the
model&#8217;s main table, not on related models. You can&#8217;t do this, for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">blog__name</span><span class="o">=</span><span class="s">&#39;foo&#39;</span><span class="p">)</span> <span class="c"># Won&#39;t work!</span>
</pre></div>
</div>
<p>Filtering based on related fields is still possible, though:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>You cannot call <tt class="docutils literal"><span class="pre">update()</span></tt> on a <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> that has had a slice taken
or can otherwise no longer be filtered.</p>
<p>The <tt class="docutils literal"><span class="pre">update()</span></tt> method returns the number of affected rows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">1</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">slug</span><span class="o">=</span><span class="s">&#39;nonexistent-slug&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">0</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="go">132</span>
</pre></div>
</div>
<p>If you&#8217;re just updating a record and don&#8217;t need to do anything with the model
object, the most efficient approach is to call <tt class="docutils literal"><span class="pre">update()</span></tt>, rather than
loading the model object into memory. For example, instead of doing this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">comments_on</span> <span class="o">=</span> <span class="bp">False</span>
<span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>...do this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">comments_on</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</pre></div>
</div>
<p>Using <tt class="docutils literal"><span class="pre">update()</span></tt> also prevents a race condition wherein something might
change in your database in the short period of time between loading the object
and calling <tt class="docutils literal"><span class="pre">save()</span></tt>.</p>
<p>Finally, realize that <tt class="docutils literal"><span class="pre">update()</span></tt> does an update at the SQL level and, thus,
does not call any <tt class="docutils literal"><span class="pre">save()</span></tt> methods on your models, nor does it emit the
<a class="reference internal" href="../signals.html#django.db.models.signals.pre_save" title="django.db.models.signals.pre_save"><tt class="xref py py-attr docutils literal"><span class="pre">pre_save</span></tt></a> or
<a class="reference internal" href="../signals.html#django.db.models.signals.post_save" title="django.db.models.signals.post_save"><tt class="xref py py-attr docutils literal"><span class="pre">post_save</span></tt></a> signals (which are a consequence of
calling <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">Model.save()</span></tt></a>). If you want to
update a bunch of records for a model that has a custom
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a> method, loop over them and call
<a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><tt class="xref py py-meth docutils literal"><span class="pre">save()</span></tt></a>, like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2010</span><span class="p">):</span>
    <span class="n">e</span><span class="o">.</span><span class="n">comments_on</span> <span class="o">=</span> <span class="bp">False</span>
    <span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-delete">
<span id="delete"></span><h4>delete<a class="headerlink" href="#delete" title="Permalink to this headline">¶</a></h4>
<dl class="method">
<dt id="django.db.models.query.QuerySet.delete">
<tt class="descname">delete</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.delete" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Performs an SQL delete query on all rows in the <a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a>. The
<tt class="docutils literal"><span class="pre">delete()</span></tt> is applied instantly. You cannot call <tt class="docutils literal"><span class="pre">delete()</span></tt> on a
<a class="reference internal" href="#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><tt class="xref py py-class docutils literal"><span class="pre">QuerySet</span></tt></a> that has had a slice taken or can otherwise no longer be
filtered.</p>
<p>For example, to delete all the entries in a particular blog:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="go"># Delete all the entries belonging to this Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>By default, Django&#8217;s <a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a> emulates the SQL
constraint <tt class="docutils literal"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">CASCADE</span></tt> — in other words, any objects with foreign
keys pointing at the objects to be deleted will be deleted along with them.
For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">blogs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="c"># This will delete all Blogs and all of their Entry objects.</span>
<span class="n">blogs</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>This cascade behavior is customizable via the
<a class="reference internal" href="fields.html#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><tt class="xref py py-attr docutils literal"><span class="pre">on_delete</span></tt></a> argument to the
<a class="reference internal" href="fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>.</p>
<p>The <tt class="docutils literal"><span class="pre">delete()</span></tt> method does a bulk delete and does not call any <tt class="docutils literal"><span class="pre">delete()</span></tt>
methods on your models. It does, however, emit the
<a class="reference internal" href="../signals.html#django.db.models.signals.pre_delete" title="django.db.models.signals.pre_delete"><tt class="xref py py-data docutils literal"><span class="pre">pre_delete</span></tt></a> and
<a class="reference internal" href="../signals.html#django.db.models.signals.post_delete" title="django.db.models.signals.post_delete"><tt class="xref py py-data docutils literal"><span class="pre">post_delete</span></tt></a> signals for all deleted objects
(including cascaded deletions).</p>
<p>Django needs to fetch objects into memory to send signals and handle cascades.
However, if there are no cascades and no signals, then Django may take a
fast-path and delete objects without fetching into memory. For large
deletes this can result in significantly reduced memory usage. The amount of
executed queries can be reduced, too.</p>
<p>ForeignKeys which are set to <a class="reference internal" href="fields.html#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><tt class="xref py py-attr docutils literal"><span class="pre">on_delete</span></tt></a>
<tt class="docutils literal"><span class="pre">DO_NOTHING</span></tt> do not prevent taking the fast-path in deletion.</p>
<p>Note that the queries generated in object deletion is an implementation
detail subject to change.</p>
</div>
<div class="section" id="s-as-manager">
<span id="as-manager"></span><h4>as_manager<a class="headerlink" href="#as-manager" title="Permalink to this headline">¶</a></h4>
<dl class="classmethod">
<dt id="django.db.models.query.QuerySet.as_manager">
<em class="property">classmethod </em><tt class="descname">as_manager</tt>()<a class="headerlink" href="#django.db.models.query.QuerySet.as_manager" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 1.7.</span> </div>
<p>Class method that returns an instance of <a class="reference internal" href="../../topics/db/managers.html#django.db.models.Manager" title="django.db.models.Manager"><tt class="xref py py-class docutils literal"><span class="pre">Manager</span></tt></a>
with a copy of the <tt class="docutils literal"><span class="pre">QuerySet</span></tt>’s methods. See
<a class="reference internal" href="../../topics/db/managers.html#create-manager-with-queryset-methods"><em>Creating Manager with QuerySet methods</em></a> for more details.</p>
</div>
</div>
<div class="section" id="s-field-lookups">
<span id="s-id4"></span><span id="field-lookups"></span><span id="id4"></span><h3>Field lookups<a class="headerlink" href="#field-lookups" title="Permalink to this headline">¶</a></h3>
<p>Field lookups are how you specify the meat of an SQL <tt class="docutils literal"><span class="pre">WHERE</span></tt> clause. They&#8217;re
specified as keyword arguments to the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> methods <a class="reference internal" href="#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><tt class="xref py py-meth docutils literal"><span class="pre">filter()</span></tt></a>,
<a class="reference internal" href="#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><tt class="xref py py-meth docutils literal"><span class="pre">exclude()</span></tt></a> and <a class="reference internal" href="#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><tt class="xref py py-meth docutils literal"><span class="pre">get()</span></tt></a>.</p>
<p>For an introduction, see <a class="reference internal" href="../../topics/db/queries.html#field-lookups-intro"><em>models and database queries documentation</em></a>.</p>
<p>Django&#8217;s inbuilt lookups are listed below. It is also possible to write
<a class="reference internal" href="../../howto/custom-lookups.html"><em>custom lookups</em></a> for model fields.</p>
<p>As a convenience when no lookup type is provided (like in
<tt class="docutils literal"><span class="pre">Entry.objects.get(id=14)</span></tt>) the lookup type is assumed to be <a class="reference internal" href="#std:fieldlookup-exact"><tt class="xref std std-lookup docutils literal"><span class="pre">exact</span></tt></a>.</p>
<div class="section" id="s-exact">
<span id="s-std:fieldlookup-exact"></span><span id="exact"></span><span id="std:fieldlookup-exact"></span><h4>exact<a class="headerlink" href="#exact" title="Permalink to this headline">¶</a></h4>
<p>Exact match. If the value provided for comparison is <tt class="docutils literal"><span class="pre">None</span></tt>, it will be
interpreted as an SQL <tt class="docutils literal"><span class="pre">NULL</span></tt> (see <a class="reference internal" href="#std:fieldlookup-isnull"><tt class="xref std std-lookup docutils literal"><span class="pre">isnull</span></tt></a> for more details).</p>
<p>Examples:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE id = 14;
SELECT ... WHERE id IS NULL;
</pre></div>
</div>
<div class="admonition-mysql-comparisons admonition">
<p class="first admonition-title">MySQL comparisons</p>
<p class="last">In MySQL, a database table&#8217;s &#8220;collation&#8221; setting determines whether
<tt class="docutils literal"><span class="pre">exact</span></tt> comparisons are case-sensitive. This is a database setting, <em>not</em>
a Django setting. It&#8217;s possible to configure your MySQL tables to use
case-sensitive comparisons, but some trade-offs are involved. For more
information about this, see the <a class="reference internal" href="../databases.html#mysql-collation"><em>collation section</em></a>
in the <a class="reference internal" href="../databases.html"><em>databases</em></a> documentation.</p>
</div>
</div>
<div class="section" id="s-iexact">
<span id="s-std:fieldlookup-iexact"></span><span id="iexact"></span><span id="std:fieldlookup-iexact"></span><h4>iexact<a class="headerlink" href="#iexact" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive exact match.</p>
<div class="versionchanged">
<span class="title">Changed in Django 1.7:</span> <p>If the value provided for comparison is <tt class="docutils literal"><span class="pre">None</span></tt>, it will be interpreted
as an SQL <tt class="docutils literal"><span class="pre">NULL</span></tt> (see <a class="reference internal" href="#std:fieldlookup-isnull"><tt class="xref std std-lookup docutils literal"><span class="pre">isnull</span></tt></a> for more details).</p>
</div>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="s">&#39;beatles blog&#39;</span><span class="p">)</span>
<span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE name ILIKE &#39;beatles blog&#39;;
SELECT ... WHERE name IS NULL;
</pre></div>
</div>
<p>Note the first query will match <tt class="docutils literal"><span class="pre">'Beatles</span> <span class="pre">Blog'</span></tt>, <tt class="docutils literal"><span class="pre">'beatles</span> <span class="pre">blog'</span></tt>,
<tt class="docutils literal"><span class="pre">'BeAtLes</span> <span class="pre">BLoG'</span></tt>, etc.</p>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> about string
comparisons. SQLite does not do case-insensitive matching for Unicode
strings.</p>
</div>
</div>
<div class="section" id="s-contains">
<span id="s-std:fieldlookup-contains"></span><span id="contains"></span><span id="std:fieldlookup-contains"></span><h4>contains<a class="headerlink" href="#contains" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive containment test.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline LIKE &#39;%Lennon%&#39;;
</pre></div>
</div>
<p>Note this will match the headline <tt class="docutils literal"><span class="pre">'Lennon</span> <span class="pre">honored</span> <span class="pre">today'</span></tt> but not <tt class="docutils literal"><span class="pre">'lennon</span>
<span class="pre">honored</span> <span class="pre">today'</span></tt>.</p>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">SQLite doesn&#8217;t support case-sensitive <tt class="docutils literal"><span class="pre">LIKE</span></tt> statements; <tt class="docutils literal"><span class="pre">contains</span></tt>
acts like <tt class="docutils literal"><span class="pre">icontains</span></tt> for SQLite. See the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> for more information.</p>
</div>
</div>
<div class="section" id="s-icontains">
<span id="s-std:fieldlookup-icontains"></span><span id="icontains"></span><span id="std:fieldlookup-icontains"></span><h4>icontains<a class="headerlink" href="#icontains" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive containment test.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__icontains</span><span class="o">=</span><span class="s">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline ILIKE &#39;%Lennon%&#39;;
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-in">
<span id="s-std:fieldlookup-in"></span><span id="in"></span><span id="std:fieldlookup-in"></span><h4>in<a class="headerlink" href="#in" title="Permalink to this headline">¶</a></h4>
<p>In a given list.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">id__in</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE id IN (1, 3, 4);
</pre></div>
</div>
<p>You can also use a queryset to dynamically evaluate the list of values
instead of providing a list of literal values:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s">&#39;Cheddar&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<p>This queryset will be evaluated as subselect statement:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE &#39;%Cheddar%&#39;)
</pre></div>
</div>
<p>If you pass in a <tt class="docutils literal"><span class="pre">ValuesQuerySet</span></tt> or <tt class="docutils literal"><span class="pre">ValuesListQuerySet</span></tt> (the result of
calling <tt class="docutils literal"><span class="pre">values()</span></tt> or <tt class="docutils literal"><span class="pre">values_list()</span></tt> on a queryset) as the value to an
<tt class="docutils literal"><span class="pre">__in</span></tt> lookup, you need to ensure you are only extracting one field in the
result. For example, this will work (filtering on the blog names):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s">&#39;Ch&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<p>This example will raise an exception, since the inner query is trying to
extract two field values, where only one is expected:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Bad code! Will raise a TypeError.</span>
<span class="n">inner_qs</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s">&#39;Ch&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s">&#39;name&#39;</span><span class="p">,</span> <span class="s">&#39;id&#39;</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name__in</span><span class="o">=</span><span class="n">inner_qs</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition-performance-considerations admonition" id="nested-queries-performance">
<p class="first admonition-title">Performance considerations</p>
<p>Be cautious about using nested queries and understand your database
server&#8217;s performance characteristics (if in doubt, benchmark!). Some
database backends, most notably MySQL, don&#8217;t optimize nested queries very
well. It is more efficient, in those cases, to extract a list of values
and then pass that into the second query. That is, execute two queries
instead of one:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">values</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
        <span class="n">name__contains</span><span class="o">=</span><span class="s">&#39;Cheddar&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values_list</span><span class="p">(</span><span class="s">&#39;pk&#39;</span><span class="p">,</span> <span class="n">flat</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__in</span><span class="o">=</span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">))</span>
</pre></div>
</div>
<p class="last">Note the <tt class="docutils literal"><span class="pre">list()</span></tt> call around the Blog <tt class="docutils literal"><span class="pre">QuerySet</span></tt> to force execution of
the first query. Without it, a nested query would be executed, because
<a class="reference internal" href="../../topics/db/queries.html#querysets-are-lazy"><em>QuerySets are lazy</em></a>.</p>
</div>
</div>
<div class="section" id="s-gt">
<span id="s-std:fieldlookup-gt"></span><span id="gt"></span><span id="std:fieldlookup-gt"></span><h4>gt<a class="headerlink" href="#gt" title="Permalink to this headline">¶</a></h4>
<p>Greater than.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">id__gt</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE id &gt; 4;
</pre></div>
</div>
</div>
<div class="section" id="s-gte">
<span id="s-std:fieldlookup-gte"></span><span id="gte"></span><span id="std:fieldlookup-gte"></span><h4>gte<a class="headerlink" href="#gte" title="Permalink to this headline">¶</a></h4>
<p>Greater than or equal to.</p>
</div>
<div class="section" id="s-lt">
<span id="s-std:fieldlookup-lt"></span><span id="lt"></span><span id="std:fieldlookup-lt"></span><h4>lt<a class="headerlink" href="#lt" title="Permalink to this headline">¶</a></h4>
<p>Less than.</p>
</div>
<div class="section" id="s-lte">
<span id="s-std:fieldlookup-lte"></span><span id="lte"></span><span id="std:fieldlookup-lte"></span><h4>lte<a class="headerlink" href="#lte" title="Permalink to this headline">¶</a></h4>
<p>Less than or equal to.</p>
</div>
<div class="section" id="s-startswith">
<span id="s-std:fieldlookup-startswith"></span><span id="startswith"></span><span id="std:fieldlookup-startswith"></span><h4>startswith<a class="headerlink" href="#startswith" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive starts-with.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s">&#39;Will&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline LIKE &#39;Will%&#39;;
</pre></div>
</div>
<p>SQLite doesn&#8217;t support case-sensitive <tt class="docutils literal"><span class="pre">LIKE</span></tt> statements; <tt class="docutils literal"><span class="pre">startswith</span></tt> acts
like <tt class="docutils literal"><span class="pre">istartswith</span></tt> for SQLite.</p>
</div>
<div class="section" id="s-istartswith">
<span id="s-std:fieldlookup-istartswith"></span><span id="istartswith"></span><span id="std:fieldlookup-istartswith"></span><h4>istartswith<a class="headerlink" href="#istartswith" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive starts-with.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__istartswith</span><span class="o">=</span><span class="s">&#39;will&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline ILIKE &#39;Will%&#39;;
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-endswith">
<span id="s-std:fieldlookup-endswith"></span><span id="endswith"></span><span id="std:fieldlookup-endswith"></span><h4>endswith<a class="headerlink" href="#endswith" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive ends-with.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__endswith</span><span class="o">=</span><span class="s">&#39;cats&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline LIKE &#39;%cats&#39;;
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">SQLite doesn&#8217;t support case-sensitive <tt class="docutils literal"><span class="pre">LIKE</span></tt> statements; <tt class="docutils literal"><span class="pre">endswith</span></tt>
acts like <tt class="docutils literal"><span class="pre">iendswith</span></tt> for SQLite. Refer to the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> documentation for more.</p>
</div>
</div>
<div class="section" id="s-iendswith">
<span id="s-std:fieldlookup-iendswith"></span><span id="iendswith"></span><span id="std:fieldlookup-iendswith"></span><h4>iendswith<a class="headerlink" href="#iendswith" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive ends-with.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__iendswith</span><span class="o">=</span><span class="s">&#39;will&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE headline ILIKE &#39;%will&#39;
</pre></div>
</div>
<div class="admonition-sqlite-users admonition">
<p class="first admonition-title">SQLite users</p>
<p class="last">When using the SQLite backend and Unicode (non-ASCII) strings, bear in
mind the <a class="reference internal" href="../databases.html#sqlite-string-matching"><em>database note</em></a> about string
comparisons.</p>
</div>
</div>
<div class="section" id="s-range">
<span id="s-std:fieldlookup-range"></span><span id="range"></span><span id="std:fieldlookup-range"></span><h4>range<a class="headerlink" href="#range" title="Permalink to this headline">¶</a></h4>
<p>Range test (inclusive).</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span>
<span class="n">start_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">end_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">31</span><span class="p">)</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__range</span><span class="o">=</span><span class="p">(</span><span class="n">start_date</span><span class="p">,</span> <span class="n">end_date</span><span class="p">))</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE pub_date BETWEEN &#39;2005-01-01&#39; and &#39;2005-03-31&#39;;
</pre></div>
</div>
<p>You can use <tt class="docutils literal"><span class="pre">range</span></tt> anywhere you can use <tt class="docutils literal"><span class="pre">BETWEEN</span></tt> in SQL — for dates,
numbers and even characters.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Filtering a <tt class="docutils literal"><span class="pre">DateTimeField</span></tt> with dates won&#8217;t include items on the last
day, because the bounds are interpreted as &#8220;0am on the given date&#8221;. If
<tt class="docutils literal"><span class="pre">pub_date</span></tt> was a <tt class="docutils literal"><span class="pre">DateTimeField</span></tt>, the above expression would be turned
into this SQL:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE pub_date BETWEEN &#39;2005-01-01 00:00:00&#39; and &#39;2005-03-31 00:00:00&#39;;
</pre></div>
</div>
<p class="last">Generally speaking, you can&#8217;t mix dates and datetimes.</p>
</div>
</div>
<div class="section" id="s-year">
<span id="s-std:fieldlookup-year"></span><span id="year"></span><span id="std:fieldlookup-year"></span><h4>year<a class="headerlink" href="#year" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact year match. Takes an integer year.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE pub_date BETWEEN &#39;2005-01-01&#39; AND &#39;2005-12-31&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, datetime fields are converted to the
current time zone before filtering.</p>
</div>
<div class="section" id="s-month">
<span id="s-std:fieldlookup-month"></span><span id="month"></span><span id="std:fieldlookup-month"></span><h4>month<a class="headerlink" href="#month" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact month match. Takes an integer 1
(January) through 12 (December).</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__month</span><span class="o">=</span><span class="mi">12</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE EXTRACT(&#39;month&#39; FROM pub_date) = &#39;12&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><em>time zone definitions
in the database</em></a>.</p>
</div>
<div class="section" id="s-day">
<span id="s-std:fieldlookup-day"></span><span id="day"></span><span id="std:fieldlookup-day"></span><h4>day<a class="headerlink" href="#day" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, an exact day match. Takes an integer day.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__day</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE EXTRACT(&#39;day&#39; FROM pub_date) = &#39;3&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>Note this will match any record with a pub_date on the third day of the month,
such as January 3, July 3, etc.</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><em>time zone definitions
in the database</em></a>.</p>
</div>
<div class="section" id="s-week-day">
<span id="s-std:fieldlookup-week_day"></span><span id="week-day"></span><span id="std:fieldlookup-week_day"></span><h4>week_day<a class="headerlink" href="#week-day" title="Permalink to this headline">¶</a></h4>
<p>For date and datetime fields, a &#8216;day of the week&#8217; match.</p>
<p>Takes an integer value representing the day of week from 1 (Sunday) to 7
(Saturday).</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__week_day</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>(No equivalent SQL code fragment is included for this lookup because
implementation of the relevant query varies among different database engines.)</p>
<p>Note this will match any record with a <tt class="docutils literal"><span class="pre">pub_date</span></tt> that falls on a Monday (day
2 of the week), regardless of the month or year in which it occurs. Week days
are indexed with day 1 being Sunday and day 7 being Saturday.</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, datetime fields are converted to the
current time zone before filtering. This requires <a class="reference internal" href="#database-time-zone-definitions"><em>time zone definitions
in the database</em></a>.</p>
</div>
<div class="section" id="s-hour">
<span id="s-std:fieldlookup-hour"></span><span id="hour"></span><span id="std:fieldlookup-hour"></span><h4>hour<a class="headerlink" href="#hour" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>For datetime fields, an exact hour match. Takes an integer between 0 and 23.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__hour</span><span class="o">=</span><span class="mi">23</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE EXTRACT(&#39;hour&#39; FROM timestamp) = &#39;23&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, values are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-minute">
<span id="s-std:fieldlookup-minute"></span><span id="minute"></span><span id="std:fieldlookup-minute"></span><h4>minute<a class="headerlink" href="#minute" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>For datetime fields, an exact minute match. Takes an integer between 0 and 59.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__minute</span><span class="o">=</span><span class="mi">29</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE EXTRACT(&#39;minute&#39; FROM timestamp) = &#39;29&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, values are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-second">
<span id="s-std:fieldlookup-second"></span><span id="second"></span><span id="std:fieldlookup-second"></span><h4>second<a class="headerlink" href="#second" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.6.</span> </div>
<p>For datetime fields, an exact second match. Takes an integer between 0 and 59.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Event</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">timestamp__second</span><span class="o">=</span><span class="mi">31</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE EXTRACT(&#39;second&#39; FROM timestamp) = &#39;31&#39;;
</pre></div>
</div>
<p>(The exact SQL syntax varies for each database engine.)</p>
<p>When <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><tt class="xref std std-setting docutils literal"><span class="pre">USE_TZ</span></tt></a> is <tt class="docutils literal"><span class="pre">True</span></tt>, values are converted to the current time
zone before filtering.</p>
</div>
<div class="section" id="s-isnull">
<span id="s-std:fieldlookup-isnull"></span><span id="isnull"></span><span id="std:fieldlookup-isnull"></span><h4>isnull<a class="headerlink" href="#isnull" title="Permalink to this headline">¶</a></h4>
<p>Takes either <tt class="docutils literal"><span class="pre">True</span></tt> or <tt class="docutils literal"><span class="pre">False</span></tt>, which correspond to SQL queries of
<tt class="docutils literal"><span class="pre">IS</span> <span class="pre">NULL</span></tt> and <tt class="docutils literal"><span class="pre">IS</span> <span class="pre">NOT</span> <span class="pre">NULL</span></tt>, respectively.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__isnull</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE pub_date IS NULL;
</pre></div>
</div>
</div>
<div class="section" id="s-search">
<span id="s-std:fieldlookup-search"></span><span id="search"></span><span id="std:fieldlookup-search"></span><h4>search<a class="headerlink" href="#search" title="Permalink to this headline">¶</a></h4>
<p>A boolean full-text search, taking advantage of full-text indexing. This is
like <a class="reference internal" href="#std:fieldlookup-contains"><tt class="xref std std-lookup docutils literal"><span class="pre">contains</span></tt></a> but is significantly faster due to full-text indexing.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__search</span><span class="o">=</span><span class="s">&quot;+Django -jazz Python&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE MATCH(tablename, headline) AGAINST (+Django -jazz Python IN BOOLEAN MODE);
</pre></div>
</div>
<p>Note this is only available in MySQL and requires direct manipulation of the
database to add the full-text index. By default Django uses BOOLEAN MODE for
full text searches. See the <a class="reference external" href="http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html">MySQL documentation</a> for additional details.</p>
</div>
<div class="section" id="s-regex">
<span id="s-std:fieldlookup-regex"></span><span id="regex"></span><span id="std:fieldlookup-regex"></span><h4>regex<a class="headerlink" href="#regex" title="Permalink to this headline">¶</a></h4>
<p>Case-sensitive regular expression match.</p>
<p>The regular expression syntax is that of the database backend in use.
In the case of SQLite, which has no built in regular expression support,
this feature is provided by a (Python) user-defined REGEXP function, and
the regular expression syntax is therefore that of Python&#8217;s <tt class="docutils literal"><span class="pre">re</span></tt> module.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">title__regex</span><span class="o">=</span><span class="s">r&#39;^(An?|The) +&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE title REGEXP BINARY &#39;^(An?|The) +&#39;; -- MySQL

SELECT ... WHERE REGEXP_LIKE(title, &#39;^(an?|the) +&#39;, &#39;c&#39;); -- Oracle

SELECT ... WHERE title ~ &#39;^(An?|The) +&#39;; -- PostgreSQL

SELECT ... WHERE title REGEXP &#39;^(An?|The) +&#39;; -- SQLite
</pre></div>
</div>
<p>Using raw strings (e.g., <tt class="docutils literal"><span class="pre">r'foo'</span></tt> instead of <tt class="docutils literal"><span class="pre">'foo'</span></tt>) for passing in the
regular expression syntax is recommended.</p>
</div>
<div class="section" id="s-iregex">
<span id="s-std:fieldlookup-iregex"></span><span id="iregex"></span><span id="std:fieldlookup-iregex"></span><h4>iregex<a class="headerlink" href="#iregex" title="Permalink to this headline">¶</a></h4>
<p>Case-insensitive regular expression match.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">title__iregex</span><span class="o">=</span><span class="s">r&#39;^(an?|the) +&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>SQL equivalents:</p>
<div class="highlight-python"><div class="highlight"><pre>SELECT ... WHERE title REGEXP &#39;^(an?|the) +&#39;; -- MySQL

SELECT ... WHERE REGEXP_LIKE(title, &#39;^(an?|the) +&#39;, &#39;i&#39;); -- Oracle

SELECT ... WHERE title ~* &#39;^(an?|the) +&#39;; -- PostgreSQL

SELECT ... WHERE title REGEXP &#39;(?i)^(an?|the) +&#39;; -- SQLite
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-aggregation-functions">
<span id="s-id5"></span><span id="aggregation-functions"></span><span id="id5"></span><h3>Aggregation functions<a class="headerlink" href="#aggregation-functions" title="Permalink to this headline">¶</a></h3>
<p>Django provides the following aggregation functions in the
<tt class="docutils literal"><span class="pre">django.db.models</span></tt> module. For details on how to use these
aggregate functions, see
<a class="reference internal" href="../../topics/db/aggregation.html"><em>the topic guide on aggregation</em></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">SQLite can&#8217;t handle aggregation on date/time fields out of the box.
This is because there are no native date/time fields in SQLite and Django
currently emulates these features using a text field. Attempts to use
aggregation on date/time fields in SQLite will raise
<tt class="docutils literal"><span class="pre">NotImplementedError</span></tt>.</p>
</div>
<div class="admonition-note admonition">
<p class="first admonition-title">Note</p>
<p class="last">Aggregation functions return <tt class="docutils literal"><span class="pre">None</span></tt> when used with an empty
<tt class="docutils literal"><span class="pre">QuerySet</span></tt>. For example, the <tt class="docutils literal"><span class="pre">Sum</span></tt> aggregation function returns <tt class="docutils literal"><span class="pre">None</span></tt>
instead of <tt class="docutils literal"><span class="pre">0</span></tt> if the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> contains no entries. An exception is
<tt class="docutils literal"><span class="pre">Count</span></tt>, which does return <tt class="docutils literal"><span class="pre">0</span></tt> if the <tt class="docutils literal"><span class="pre">QuerySet</span></tt> is empty.</p>
</div>
<div class="section" id="s-avg">
<span id="avg"></span><h4>Avg<a class="headerlink" href="#avg" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Avg">
<em class="property">class </em><tt class="descname">Avg</tt>(<em>field</em>)<a class="headerlink" href="#django.db.models.Avg" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the mean value of the given field, which must be numeric.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__avg</span></tt></li>
<li>Return type: <tt class="docutils literal"><span class="pre">float</span></tt></li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-id6">
<span id="id6"></span><h4>Count<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Count">
<em class="property">class </em><tt class="descname">Count</tt>(<em>field</em>, <em>distinct=False</em>)<a class="headerlink" href="#django.db.models.Count" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of objects that are related through the provided field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__count</span></tt></li>
<li>Return type: <tt class="docutils literal"><span class="pre">int</span></tt></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.Count.distinct">
<tt class="descname">distinct</tt><a class="headerlink" href="#django.db.models.Count.distinct" title="Permalink to this definition">¶</a></dt>
<dd><p>If <tt class="docutils literal"><span class="pre">distinct=True</span></tt>, the count will only include unique instances.
This is the SQL equivalent of <tt class="docutils literal"><span class="pre">COUNT(DISTINCT</span> <span class="pre">&lt;field&gt;)</span></tt>. The default
value is <tt class="docutils literal"><span class="pre">False</span></tt>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="s-max">
<span id="max"></span><h4>Max<a class="headerlink" href="#max" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Max">
<em class="property">class </em><tt class="descname">Max</tt>(<em>field</em>)<a class="headerlink" href="#django.db.models.Max" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the maximum value of the given field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__max</span></tt></li>
<li>Return type: same as input field</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-min">
<span id="min"></span><h4>Min<a class="headerlink" href="#min" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Min">
<em class="property">class </em><tt class="descname">Min</tt>(<em>field</em>)<a class="headerlink" href="#django.db.models.Min" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the minimum value of the given field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__min</span></tt></li>
<li>Return type: same as input field</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-stddev">
<span id="stddev"></span><h4>StdDev<a class="headerlink" href="#stddev" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.StdDev">
<em class="property">class </em><tt class="descname">StdDev</tt>(<em>field</em>, <em>sample=False</em>)<a class="headerlink" href="#django.db.models.StdDev" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the standard deviation of the data in the provided field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__stddev</span></tt></li>
<li>Return type: <tt class="docutils literal"><span class="pre">float</span></tt></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.StdDev.sample">
<tt class="descname">sample</tt><a class="headerlink" href="#django.db.models.StdDev.sample" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, <tt class="docutils literal"><span class="pre">StdDev</span></tt> returns the population standard deviation. However,
if <tt class="docutils literal"><span class="pre">sample=True</span></tt>, the return value will be the sample standard deviation.</p>
</dd></dl>

<div class="admonition-sqlite admonition">
<p class="first admonition-title">SQLite</p>
<p class="last">SQLite doesn&#8217;t provide <tt class="docutils literal"><span class="pre">StdDev</span></tt> out of the box. An implementation
is available as an extension module for SQLite. Consult the <a class="reference external" href="http://www.sqlite.org/contrib">SQlite
documentation</a> for instructions on obtaining and installing this
extension.</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-sum">
<span id="sum"></span><h4>Sum<a class="headerlink" href="#sum" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Sum">
<em class="property">class </em><tt class="descname">Sum</tt>(<em>field</em>)<a class="headerlink" href="#django.db.models.Sum" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes the sum of all values of the given field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__sum</span></tt></li>
<li>Return type: same as input field</li>
</ul>
</dd></dl>

</div>
<div class="section" id="s-variance">
<span id="variance"></span><h4>Variance<a class="headerlink" href="#variance" title="Permalink to this headline">¶</a></h4>
<dl class="class">
<dt id="django.db.models.Variance">
<em class="property">class </em><tt class="descname">Variance</tt>(<em>field</em>, <em>sample=False</em>)<a class="headerlink" href="#django.db.models.Variance" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the variance of the data in the provided field.</p>
<ul class="simple">
<li>Default alias: <tt class="docutils literal"><span class="pre">&lt;field&gt;__variance</span></tt></li>
<li>Return type: <tt class="docutils literal"><span class="pre">float</span></tt></li>
</ul>
<p>Has one optional argument:</p>
<dl class="attribute">
<dt id="django.db.models.Variance.sample">
<tt class="descname">sample</tt><a class="headerlink" href="#django.db.models.Variance.sample" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, <tt class="docutils literal"><span class="pre">Variance</span></tt> returns the population variance. However,
if <tt class="docutils literal"><span class="pre">sample=True</span></tt>, the return value will be the sample variance.</p>
</dd></dl>

<div class="admonition-sqlite admonition">
<p class="first admonition-title">SQLite</p>
<p class="last">SQLite doesn&#8217;t provide <tt class="docutils literal"><span class="pre">Variance</span></tt> out of the box. An implementation
is available as an extension module for SQLite. Consult the <a class="reference external" href="http://www.sqlite.org/contrib">SQlite
documentation</a> for instructions on obtaining and installing this
extension.</p>
</div>
</dd></dl>

</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">QuerySet API reference</a><ul>
<li><a class="reference internal" href="#when-querysets-are-evaluated">When QuerySets are evaluated</a><ul>
<li><a class="reference internal" href="#pickling-querysets">Pickling QuerySets</a></li>
</ul>
</li>
<li><a class="reference internal" href="#queryset-api">QuerySet API</a><ul>
<li><a class="reference internal" href="#methods-that-return-new-querysets">Methods that return new QuerySets</a><ul>
<li><a class="reference internal" href="#filter">filter</a></li>
<li><a class="reference internal" href="#exclude">exclude</a></li>
<li><a class="reference internal" href="#annotate">annotate</a></li>
<li><a class="reference internal" href="#order-by">order_by</a></li>
<li><a class="reference internal" href="#reverse">reverse</a></li>
<li><a class="reference internal" href="#distinct">distinct</a></li>
<li><a class="reference internal" href="#values">values</a></li>
<li><a class="reference internal" href="#values-list">values_list</a></li>
<li><a class="reference internal" href="#dates">dates</a></li>
<li><a class="reference internal" href="#datetimes">datetimes</a></li>
<li><a class="reference internal" href="#none">none</a></li>
<li><a class="reference internal" href="#all">all</a></li>
<li><a class="reference internal" href="#select-related">select_related</a></li>
<li><a class="reference internal" href="#prefetch-related">prefetch_related</a></li>
<li><a class="reference internal" href="#extra">extra</a></li>
<li><a class="reference internal" href="#defer">defer</a></li>
<li><a class="reference internal" href="#only">only</a></li>
<li><a class="reference internal" href="#using">using</a></li>
<li><a class="reference internal" href="#select-for-update">select_for_update</a></li>
<li><a class="reference internal" href="#raw">raw</a></li>
</ul>
</li>
<li><a class="reference internal" href="#methods-that-do-not-return-querysets">Methods that do not return QuerySets</a><ul>
<li><a class="reference internal" href="#get">get</a></li>
<li><a class="reference internal" href="#create">create</a></li>
<li><a class="reference internal" href="#get-or-create">get_or_create</a></li>
<li><a class="reference internal" href="#update-or-create">update_or_create</a></li>
<li><a class="reference internal" href="#bulk-create">bulk_create</a></li>
<li><a class="reference internal" href="#count">count</a></li>
<li><a class="reference internal" href="#in-bulk">in_bulk</a></li>
<li><a class="reference internal" href="#iterator">iterator</a></li>
<li><a class="reference internal" href="#latest">latest</a></li>
<li><a class="reference internal" href="#earliest">earliest</a></li>
<li><a class="reference internal" href="#first">first</a></li>
<li><a class="reference internal" href="#last">last</a></li>
<li><a class="reference internal" href="#aggregate">aggregate</a></li>
<li><a class="reference internal" href="#exists">exists</a></li>
<li><a class="reference internal" href="#update">update</a></li>
<li><a class="reference internal" href="#delete">delete</a></li>
<li><a class="reference internal" href="#as-manager">as_manager</a></li>
</ul>
</li>
<li><a class="reference internal" href="#field-lookups">Field lookups</a><ul>
<li><a class="reference internal" href="#exact">exact</a></li>
<li><a class="reference internal" href="#iexact">iexact</a></li>
<li><a class="reference internal" href="#contains">contains</a></li>
<li><a class="reference internal" href="#icontains">icontains</a></li>
<li><a class="reference internal" href="#in">in</a></li>
<li><a class="reference internal" href="#gt">gt</a></li>
<li><a class="reference internal" href="#gte">gte</a></li>
<li><a class="reference internal" href="#lt">lt</a></li>
<li><a class="reference internal" href="#lte">lte</a></li>
<li><a class="reference internal" href="#startswith">startswith</a></li>
<li><a class="reference internal" href="#istartswith">istartswith</a></li>
<li><a class="reference internal" href="#endswith">endswith</a></li>
<li><a class="reference internal" href="#iendswith">iendswith</a></li>
<li><a class="reference internal" href="#range">range</a></li>
<li><a class="reference internal" href="#year">year</a></li>
<li><a class="reference internal" href="#month">month</a></li>
<li><a class="reference internal" href="#day">day</a></li>
<li><a class="reference internal" href="#week-day">week_day</a></li>
<li><a class="reference internal" href="#hour">hour</a></li>
<li><a class="reference internal" href="#minute">minute</a></li>
<li><a class="reference internal" href="#second">second</a></li>
<li><a class="reference internal" href="#isnull">isnull</a></li>
<li><a class="reference internal" href="#search">search</a></li>
<li><a class="reference internal" href="#regex">regex</a></li>
<li><a class="reference internal" href="#iregex">iregex</a></li>
</ul>
</li>
<li><a class="reference internal" href="#aggregation-functions">Aggregation functions</a><ul>
<li><a class="reference internal" href="#avg">Avg</a></li>
<li><a class="reference internal" href="#id6">Count</a></li>
<li><a class="reference internal" href="#max">Max</a></li>
<li><a class="reference internal" href="#min">Min</a></li>
<li><a class="reference internal" href="#stddev">StdDev</a></li>
<li><a class="reference internal" href="#sum">Sum</a></li>
<li><a class="reference internal" href="#variance">Variance</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="instances.html">Model instance reference</a></li>
    
    
      <li>Next: <a href="queries.html">Query-related classes</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="../index.html">API Reference</a>
        
          <ul><li><a href="index.html">Models</a>
        
        <ul><li>QuerySet API reference</li></ul>
        </li></ul></li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../../_sources/ref/models/querysets.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="instances.html" title="Model instance reference">previous</a>
     |
    <a href="../index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="queries.html" title="Query-related classes">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>